BuntDB is an embeddable, in-memory key/value database for Go with custom indexing and geospatial support

BuntDB
Go Report Card Godoc LICENSE

BuntDB is a low-level, in-memory, key/value store in pure Go. It persists to disk, is ACID compliant, and uses locking for multiple readers and a single writer. It supports custom indexes and geospatial data. It's ideal for projects that need a dependable database and favor speed over data size.

Features

Getting Started

Installing

To start using BuntDB, install Go and run go get:

$ go get -u github.com/tidwall/buntdb

This will retrieve the library.

Opening a database

The primary object in BuntDB is a DB. To open or create your database, use the buntdb.Open() function:

package main

import (
	"log"

	"github.com/tidwall/buntdb"
)

func main() {
	// Open the data.db file. It will be created if it doesn't exist.
	db, err := buntdb.Open("data.db")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	...
}

It's also possible to open a database that does not persist to disk by using :memory: as the path of the file.

buntdb.Open(":memory:") // Open a file that does not persist to disk.

Transactions

All reads and writes must be performed from inside a transaction. BuntDB can have one write transaction opened at a time, but can have many concurrent read transactions. Each transaction maintains a stable view of the database. In other words, once a transaction has begun, the data for that transaction cannot be changed by other transactions.

Transactions run in a function that exposes a Tx object, which represents the transaction state. While inside a transaction, all database operations should be performed using this object. You should never access the origin DB object while inside a transaction. Doing so may have side-effects, such as blocking your application.

When a transaction fails, it will roll back, and revert all changes that occurred to the database during that transaction. There's a single return value that you can use to close the transaction. For read/write transactions, returning an error this way will force the transaction to roll back. When a read/write transaction succeeds all changes are persisted to disk.

Read-only Transactions

A read-only transaction should be used when you don't need to make changes to the data. The advantage of a read-only transaction is that there can be many running concurrently.

err := db.View(func(tx *buntdb.Tx) error {
	...
	return nil
})

Read/write Transactions

A read/write transaction is used when you need to make changes to your data. There can only be one read/write transaction running at a time. So make sure you close it as soon as you are done with it.

err := db.Update(func(tx *buntdb.Tx) error {
	...
	return nil
})

Setting and getting key/values

To set a value you must open a read/write transaction:

err := db.Update(func(tx *buntdb.Tx) error {
	_, _, err := tx.Set("mykey", "myvalue", nil)
	return err
})

To get the value:

err := db.View(func(tx *buntdb.Tx) error {
	val, err := tx.Get("mykey")
	if err != nil{
		return err
	}
	fmt.Printf("value is %s\n", val)
	return nil
})

Getting non-existent values will cause an ErrNotFound error.

Iterating

All keys/value pairs are ordered in the database by the key. To iterate over the keys:

err := db.View(func(tx *buntdb.Tx) error {
	err := tx.Ascend("", func(key, value string) bool {
		fmt.Printf("key: %s, value: %s\n", key, value)
	})
	return err
})

There is also AscendGreaterOrEqual, AscendLessThan, AscendRange, AscendEqual, Descend, DescendLessOrEqual, DescendGreaterThan, DescendRange, and DescendEqual. Please see the documentation for more information on these functions.

Custom Indexes

Initially all data is stored in a single B-tree with each item having one key and one value. All of these items are ordered by the key. This is great for quickly getting a value from a key or iterating over the keys. Feel free to peruse the B-tree implementation.

You can also create custom indexes that allow for ordering and iterating over values. A custom index also uses a B-tree, but it's more flexible because it allows for custom ordering.

For example, let's say you want to create an index for ordering names:

db.CreateIndex("names", "*", buntdb.IndexString)

This will create an index named names which stores and sorts all values. The second parameter is a pattern that is used to filter on keys. A * wildcard argument means that we want to accept all keys. IndexString is a built-in function that performs case-insensitive ordering on the values

Now you can add various names:

db.Update(func(tx *buntdb.Tx) error {
	tx.Set("user:0:name", "tom", nil)
	tx.Set("user:1:name", "Randi", nil)
	tx.Set("user:2:name", "jane", nil)
	tx.Set("user:4:name", "Janet", nil)
	tx.Set("user:5:name", "Paula", nil)
	tx.Set("user:6:name", "peter", nil)
	tx.Set("user:7:name", "Terri", nil)
	return nil
})

Finally you can iterate over the index:

db.View(func(tx *buntdb.Tx) error {
	tx.Ascend("names", func(key, val string) bool {
	fmt.Printf(buf, "%s %s\n", key, val)
		return true
	})
	return nil
})

The output should be:

user:2:name jane
user:4:name Janet
user:5:name Paula
user:6:name peter
user:1:name Randi
user:7:name Terri
user:0:name tom

The pattern parameter can be used to filter on keys like this:

db.CreateIndex("names", "user:*", buntdb.IndexString)

Now only items with keys that have the prefix user: will be added to the names index.

Built-in types

Along with IndexString, there is also IndexInt, IndexUint, and IndexFloat. These are built-in types for indexing. You can choose to use these or create your own.

So to create an index that is numerically ordered on an age key, we could use:

db.CreateIndex("ages", "user:*:age", buntdb.IndexInt)

And then add values:

db.Update(func(tx *buntdb.Tx) error {
	tx.Set("user:0:age", "35", nil)
	tx.Set("user:1:age", "49", nil)
	tx.Set("user:2:age", "13", nil)
	tx.Set("user:4:age", "63", nil)
	tx.Set("user:5:age", "8", nil)
	tx.Set("user:6:age", "3", nil)
	tx.Set("user:7:age", "16", nil)
	return nil
})
db.View(func(tx *buntdb.Tx) error {
	tx.Ascend("ages", func(key, val string) bool {
	fmt.Printf(buf, "%s %s\n", key, val)
		return true
	})
	return nil
})

The output should be:

user:6:age 3
user:5:age 8
user:2:age 13
user:7:age 16
user:0:age 35
user:1:age 49
user:4:age 63

Spatial Indexes

BuntDB has support for spatial indexes by storing rectangles in an R-tree. An R-tree is organized in a similar manner as a B-tree, and both are balanced trees. But, an R-tree is special because it can operate on data that is in multiple dimensions. This is super handy for Geospatial applications.

To create a spatial index use the CreateSpatialIndex function:

db.CreateSpatialIndex("fleet", "fleet:*:pos", buntdb.IndexRect)

Then IndexRect is a built-in function that converts rect strings to a format that the R-tree can use. It's easy to use this function out of the box, but you might find it better to create a custom one that renders from a different format, such as Well-known text or GeoJSON.

To add some lon,lat points to the fleet index:

db.Update(func(tx *buntdb.Tx) error {
	tx.Set("fleet:0:pos", "[-115.567 33.532]", nil)
	tx.Set("fleet:1:pos", "[-116.671 35.735]", nil)
	tx.Set("fleet:2:pos", "[-113.902 31.234]", nil)
	return nil
})

And then you can run the Intersects function on the index:

db.View(func(tx *buntdb.Tx) error {
	tx.Intersects("fleet", "[-117 30],[-112 36]", func(key, val string) bool {
		...
		return true
	})
	return nil
})

This will get all three positions.

k-Nearest Neighbors

Use the Nearby function to get all the positions in order of nearest to farthest :

db.View(func(tx *buntdb.Tx) error {
	tx.Nearby("fleet", "[-113 33]", func(key, val string, dist float64) bool {
		...
		return true
	})
	return nil
})

Spatial bracket syntax

The bracket syntax [-117 30],[-112 36] is unique to BuntDB, and it's how the built-in rectangles are processed. But, you are not limited to this syntax. Whatever Rect function you choose to use during CreateSpatialIndex will be used to process the parameter, in this case it's IndexRect.

  • 2D rectangle: [10 15],[20 25] Min XY: "10x15", Max XY: "20x25"

  • 3D rectangle: [10 15 12],[20 25 18] Min XYZ: "10x15x12", Max XYZ: "20x25x18"

  • 2D point: [10 15] XY: "10x15"

  • LonLat point: [-112.2693 33.5123] LatLon: "33.5123 -112.2693"

  • LonLat bounding box: [-112.26 33.51],[-112.18 33.67] Min LatLon: "33.51 -112.26", Max LatLon: "33.67 -112.18"

Notice: The longitude is the Y axis and is on the left, and latitude is the X axis and is on the right.

You can also represent Infinity by using -inf and +inf. For example, you might have the following points ([X Y M] where XY is a point and M is a timestamp):

[3 9 1]
[3 8 2]
[4 8 3]
[4 7 4]
[5 7 5]
[5 6 6]

You can then do a search for all points with M between 2-4 by calling Intersects.

tx.Intersects("points", "[-inf -inf 2],[+inf +inf 4]", func(key, val string) bool {
	println(val)
	return true
})

Which will return:

[3 8 2]
[4 8 3]
[4 7 4]

JSON Indexes

Indexes can be created on individual fields inside JSON documents. BuntDB uses GJSON under the hood.

For example:

package main

import (
	"fmt"

	"github.com/tidwall/buntdb"
)

func main() {
	db, _ := buntdb.Open(":memory:")
	db.CreateIndex("last_name", "*", buntdb.IndexJSON("name.last"))
	db.CreateIndex("age", "*", buntdb.IndexJSON("age"))
	db.Update(func(tx *buntdb.Tx) error {
		tx.Set("1", `{"name":{"first":"Tom","last":"Johnson"},"age":38}`, nil)
		tx.Set("2", `{"name":{"first":"Janet","last":"Prichard"},"age":47}`, nil)
		tx.Set("3", `{"name":{"first":"Carol","last":"Anderson"},"age":52}`, nil)
		tx.Set("4", `{"name":{"first":"Alan","last":"Cooper"},"age":28}`, nil)
		return nil
	})
	db.View(func(tx *buntdb.Tx) error {
		fmt.Println("Order by last name")
		tx.Ascend("last_name", func(key, value string) bool {
			fmt.Printf("%s: %s\n", key, value)
			return true
		})
		fmt.Println("Order by age")
		tx.Ascend("age", func(key, value string) bool {
			fmt.Printf("%s: %s\n", key, value)
			return true
		})
		fmt.Println("Order by age range 30-50")
		tx.AscendRange("age", `{"age":30}`, `{"age":50}`, func(key, value string) bool {
			fmt.Printf("%s: %s\n", key, value)
			return true
		})
		return nil
	})
}

Results:

Order by last name
3: {"name":{"first":"Carol","last":"Anderson"},"age":52}
4: {"name":{"first":"Alan","last":"Cooper"},"age":28}
1: {"name":{"first":"Tom","last":"Johnson"},"age":38}
2: {"name":{"first":"Janet","last":"Prichard"},"age":47}

Order by age
4: {"name":{"first":"Alan","last":"Cooper"},"age":28}
1: {"name":{"first":"Tom","last":"Johnson"},"age":38}
2: {"name":{"first":"Janet","last":"Prichard"},"age":47}
3: {"name":{"first":"Carol","last":"Anderson"},"age":52}

Order by age range 30-50
1: {"name":{"first":"Tom","last":"Johnson"},"age":38}
2: {"name":{"first":"Janet","last":"Prichard"},"age":47}

Multi Value Index

With BuntDB it's possible to join multiple values on a single index. This is similar to a multi column index in a traditional SQL database.

In this example we are creating a multi value index on "name.last" and "age":

db, _ := buntdb.Open(":memory:")
db.CreateIndex("last_name_age", "*", buntdb.IndexJSON("name.last"), buntdb.IndexJSON("age"))
db.Update(func(tx *buntdb.Tx) error {
	tx.Set("1", `{"name":{"first":"Tom","last":"Johnson"},"age":38}`, nil)
	tx.Set("2", `{"name":{"first":"Janet","last":"Prichard"},"age":47}`, nil)
	tx.Set("3", `{"name":{"first":"Carol","last":"Anderson"},"age":52}`, nil)
	tx.Set("4", `{"name":{"first":"Alan","last":"Cooper"},"age":28}`, nil)
	tx.Set("5", `{"name":{"first":"Sam","last":"Anderson"},"age":51}`, nil)
	tx.Set("6", `{"name":{"first":"Melinda","last":"Prichard"},"age":44}`, nil)
	return nil
})
db.View(func(tx *buntdb.Tx) error {
	tx.Ascend("last_name_age", func(key, value string) bool {
		fmt.Printf("%s: %s\n", key, value)
		return true
	})
	return nil
})

// Output:
// 5: {"name":{"first":"Sam","last":"Anderson"},"age":51}
// 3: {"name":{"first":"Carol","last":"Anderson"},"age":52}
// 4: {"name":{"first":"Alan","last":"Cooper"},"age":28}
// 1: {"name":{"first":"Tom","last":"Johnson"},"age":38}
// 6: {"name":{"first":"Melinda","last":"Prichard"},"age":44}
// 2: {"name":{"first":"Janet","last":"Prichard"},"age":47}

Descending Ordered Index

Any index can be put in descending order by wrapping it's less function with buntdb.Desc.

db.CreateIndex("last_name_age", "*",
buntdb.IndexJSON("name.last"),
buntdb.Desc(buntdb.IndexJSON("age")))

This will create a multi value index where the last name is ascending and the age is descending.

Collate i18n Indexes

Using the external collate package it's possible to create indexes that are sorted by the specified language. This is similar to the SQL COLLATE keyword found in traditional databases.

To install:

go get -u github.com/tidwall/collate

For example:

import "github.com/tidwall/collate"

// To sort case-insensitive in French.
db.CreateIndex("name", "*", collate.IndexString("FRENCH_CI"))

// To specify that numbers should sort numerically ("2" < "12")
// and use a comma to represent a decimal point.
db.CreateIndex("amount", "*", collate.IndexString("FRENCH_NUM"))

There's also support for Collation on JSON indexes:

db.CreateIndex("last_name", "*", collate.IndexJSON("CHINESE_CI", "name.last"))

Check out the collate project for more information.

Data Expiration

Items can be automatically evicted by using the SetOptions object in the Set function to set a TTL.

db.Update(func(tx *buntdb.Tx) error {
	tx.Set("mykey", "myval", &buntdb.SetOptions{Expires:true, TTL:time.Second})
	return nil
})

Now mykey will automatically be deleted after one second. You can remove the TTL by setting the value again with the same key/value, but with the options parameter set to nil.

Delete while iterating

BuntDB does not currently support deleting a key while in the process of iterating. As a workaround you'll need to delete keys following the completion of the iterator.

var delkeys []string
tx.AscendKeys("object:*", func(k, v string) bool {
	if someCondition(k) == true {
		delkeys = append(delkeys, k)
	}
	return true // continue
})
for _, k := range delkeys {
	if _, err = tx.Delete(k); err != nil {
		return err
	}
}

Append-only File

BuntDB uses an AOF (append-only file) which is a log of all database changes that occur from operations like Set() and Delete().

The format of this file looks like:

set key:1 value1
set key:2 value2
set key:1 value3
del key:2
...

When the database opens again, it will read back the aof file and process each command in exact order. This read process happens one time when the database opens. From there on the file is only appended.

As you may guess this log file can grow large over time. There's a background routine that automatically shrinks the log file when it gets too large. There is also a Shrink() function which will rewrite the aof file so that it contains only the items in the database. The shrink operation does not lock up the database so read and write transactions can continue while shrinking is in process.

Durability and fsync

By default BuntDB executes an fsync once every second on the aof file. Which simply means that there's a chance that up to one second of data might be lost. If you need higher durability then there's an optional database config setting Config.SyncPolicy which can be set to Always.

The Config.SyncPolicy has the following options:

  • Never - fsync is managed by the operating system, less safe
  • EverySecond - fsync every second, fast and safer, this is the default
  • Always - fsync after every write, very durable, slower

Config

Here are some configuration options that can be use to change various behaviors of the database.

  • SyncPolicy adjusts how often the data is synced to disk. This value can be Never, EverySecond, or Always. Default is EverySecond.
  • AutoShrinkPercentage is used by the background process to trigger a shrink of the aof file when the size of the file is larger than the percentage of the result of the previous shrunk file. For example, if this value is 100, and the last shrink process resulted in a 100mb file, then the new aof file must be 200mb before a shrink is triggered. Default is 100.
  • AutoShrinkMinSize defines the minimum size of the aof file before an automatic shrink can occur. Default is 32MB.
  • AutoShrinkDisabled turns off automatic background shrinking. Default is false.

To update the configuration you should call ReadConfig followed by SetConfig. For example:

var config buntdb.Config
if err := db.ReadConfig(&config); err != nil{
	log.Fatal(err)
}
if err := db.SetConfig(config); err != nil{
	log.Fatal(err)
}

Performance

How fast is BuntDB?

Here are some example benchmarks when using BuntDB in a Raft Store implementation.

You can also run the standard Go benchmark tool from the project root directory:

go test --bench=.

BuntDB-Benchmark

There's a custom utility that was created specifically for benchmarking BuntDB.

These are the results from running the benchmarks on a MacBook Pro 15" 2.8 GHz Intel Core i7:

$ buntdb-benchmark -q
GET: 4609604.74 operations per second
SET: 248500.33 operations per second
ASCEND_100: 2268998.79 operations per second
ASCEND_200: 1178388.14 operations per second
ASCEND_400: 679134.20 operations per second
ASCEND_800: 348445.55 operations per second
DESCEND_100: 2313821.69 operations per second
DESCEND_200: 1292738.38 operations per second
DESCEND_400: 675258.76 operations per second
DESCEND_800: 337481.67 operations per second
SPATIAL_SET: 134824.60 operations per second
SPATIAL_INTERSECTS_100: 939491.47 operations per second
SPATIAL_INTERSECTS_200: 561590.40 operations per second
SPATIAL_INTERSECTS_400: 306951.15 operations per second
SPATIAL_INTERSECTS_800: 159673.91 operations per second

To install this utility:

go get github.com/tidwall/buntdb-benchmark

Contact

Josh Baker @tidwall

License

BuntDB source code is available under the MIT License.

Comments
  • documentation mark and question

    documentation mark and question

    Hi,

    2D point: [10 15 12] this will be 2D point: [10 15].

    Question: Is it possible/correct to use the 2D point spatial index as data time range? For example, [startTime stopTime] UnixNano --> int64 as XY.

  • Sliding Expiration and Callback

    Sliding Expiration and Callback

    This is a feature request - if it's proper to add them.

    1. Adding sliding TTL; on each get operation, if the entry has a TTL and a sliding flag is set, the absolute internal expiration time will be shifted into future.
    2. Setting a callback like func(key, value string) that will be called (in it's own new goroutine) when an entry gets expired.

    Since these are optional, they would affect performance only if they are present.

  • Advice? Slow JSON unmarshalling because of string -> []bytes

    Advice? Slow JSON unmarshalling because of string -> []bytes

    I wonder if anyone can offer any advice.

    I've been doing extensive benchmarking of different Go KV stores for an ERP application. I am saving millions of 'transactions' serialised with JSON, reading them back, deserialising and running some aggregation operations.

    I was comparing Bunt to BadgerDB and finding that Badger was 4x faster for my benchmark for reading and aggregating, which seemed odd to me.

    After a little digging, I realised that if I removed the JSON unmarshalling step, Bunt became 2x faster than Badger. Obviously I am using the same JSON unmarshalling technique in both cases.

    The problem lies in the fact that Bunt returns strings whereas Badger returns []byte. This introduces another step in the deserialisation for Bunt json.Unmarshal([]byte(value), &order) which is what is causing the slowdown on the Bunt benchmark.

    Ive Googled about a bit and understand that the string -> []byte conversion is costly, and have come across some solutions involving unsafe, but haven't been able to get them to work for me.

    Has anyone tackled this issue and come up with a good solution. BadgerDB is really nice, but Bunt's indexing functionality is just what I'm looking for and would really love to choose it for this project. I can see that the raw iteration speed is faster than Badger - its just this string issue thats causing the slower aggregation.

  • Question: Retrieve by index

    Question: Retrieve by index

    How to select data for condition - json field absent ?

        db.CreateIndex("age", "*", buntdb.IndexJSON("age"))
           tx.Set("5", `{"name":{"first":"Alan"},"age":28}`, nil)
            tx.Set("6", `{"name":{"first":"Dred"}}`, nil)
    

    How to get number key=6 by age == nil?

    And second question how to get key=5 by exact value age=28 ?

  • auto-shrink not triggered

    auto-shrink not triggered

    This may be a duplicate of #37. I'm running v1.2.4. I have a database with only 37 actual entries (the workload is rapid repeated updates to a small set of keys). I'm using the default config, but autoshrink is not triggering despite the database reaching 171MB in size.

    I added some prints here:

    https://github.com/tidwall/buntdb/blob/v1.2.4/buntdb.go#L566

    and both aofsz and db.lastaofsz are set to the file size (currently 178954614), so shrink evaluates to false. I'm not sure whether the condition is buggy, or whether db.lastaofsz is being maintained incorrectly?

    Thanks for your time.

  • Attempting to use AscendEqual

    Attempting to use AscendEqual

    I'm trying to use the AscendEqual function to iterate through entries, but it's not returning the results I'm expecting. I've narrowed the issue down to the following large-ish (sorry) test case:

    func TestNameEquals(t *testing.T) {
    	iter := func(key, value string) bool {
    		i, _ := strconv.Atoi(key)
    		fmt.Printf("%2d - %v\n", i, value)
    		return true
    	}
    
    	j := func(v string, a int) string {
    		return fmt.Sprintf("{\"name\":\"%v\", \"age\":%v}", v, a)
    	}
    
    	name := func(v string) string {
    		return fmt.Sprintf("{\"name\":\"%v\"}", v)
    	}
    
    	db, _ := buntdb.Open(":memory:")
    	db.CreateIndex("name", "*",
    		buntdb.IndexJSON("name"),
    		buntdb.IndexJSON("age"),
    	)
    	db.Update(func(tx *buntdb.Tx) error {
    		tx.Set("1", j("bob", 42), nil)
    		tx.Set("2", j("james", 55), nil)
    		tx.Set("4", j("logan", 14), nil)
    		tx.Set("11", j("james", 11), nil)
    		tx.Set("3", j("clark", 33), nil)
    		tx.Set("5", j("tommy", 15), nil)
    		tx.Set("6", j("zane", 19), nil)
    		return nil
    	})
    
    	db.View(func(tx *buntdb.Tx) error {
    		fmt.Println(" -- Greater than d")
    		tx.AscendGreaterOrEqual("name", name("d"), iter)
    
    		fmt.Println(" -- Equals James")
    		tx.AscendEqual("name", name("james"), iter)
    
    		return nil
    	})
    }
    

    The output from running the test case is:

    === RUN   TestNameEquals
     -- Greater than d
    11 - {"name":"james", "age":11}
     2 - {"name":"james", "age":55}
     4 - {"name":"logan", "age":14}
     5 - {"name":"tommy", "age":15}
     6 - {"name":"zane", "age":19}
     -- Equals James
    --- PASS: TestNameEquals (0.00s)
    

    AscendGreaterOrEqual works exactly as expected, but I was hoping that AscendEqual would allow me to iterate only the james entries sorted by the age field. Have I misunderstood the purpose of the function?

  • Is there a another way to avoid with deprecate warning ?

    Is there a another way to avoid with deprecate warning ?

    Thanks in advance.. I'm new to buntdb. but while Testng example code, I got a message about deprecated method. for example, below .... db.CreateIndex("ages", "user:*:age", buntdb.IndexInt)

    readme.md is too old ? if not, (in source code) comment is misspelled ?

  • Key not found error even when the key is present in the corresponding file

    Key not found error even when the key is present in the corresponding file

    Hi, is there any reason why a stored key-value pair is not found even though the key is present in the DB file? My use case is as follows:

    1. A server writing key-value pairs to this file
    2. Go tests updating the file

    Any help would be appreciated. Thanks.

  • data expiration

    data expiration

    It seems like the expiration only works as long as the program does not exit before the expiration.

    If I set a key to expire in 10 seconds and the program finishes in 5 I can run it as many times as I want without the expiration ever happening. Is this intentional?

  • Invalid descend range result

    Invalid descend range result

    hello, tidwall I hoped to get the ascend results is right when I was using tx.AscendRange or tx.DescendRange fuction. But when i hoped to get the descend results, it's nil of return. Can you help me? thanks.

    db, _ := buntdb.Open(":memory:")
    	db.Update(func(tx *buntdb.Tx) error {
    		tx.CreateIndex("last_name", "*", buntdb.IndexJSON("name.last"))
    		
    		tx.Set("1", `{"name":{"first":"Tom","last":"Johnson"},"age":"38"}`, nil)
    		tx.Set("2", `{"name":{"first":"Janet","last":"Prichard"},"age":"47"}`, nil)
    		tx.Set("3", `{"name":{"first":"Carol","last":"Anderson"},"age":"52"}`, nil)
    		tx.Set("4", `{"name":{"first":"Alan","last":"Cooper"},"age":"28"}`, nil)
    		tx.Set("5", `{"name":{"first":"Jack","last":"Ma"},"age":"20"}`, nil)
    		tx.Set("6", `{"name":{"first":"Blues","last":"Li"},"age":"31"}`, nil)
    		tx.Set("7", `{"name":{"first":"Pony","last":"Ma"},"age":"3"}`, nil)
    		tx.Set("8", `{"name":{"first":"Robin","last":"Li"},"age":"2"}`, nil)
    		tx.Set("9", `{"name":{"first":"Larry","last":"Liu"},"age":""}`, nil)
    		return nil
    	})
    
    	db.View(func(tx *buntdb.Tx) error {
    		fmt.Println("---------------------")
    		tx.Descend("last_name", func(key, value string) bool {
    			fmt.Printf("%s: %s\n", key, value)
    			return true
    		})
    		
    		fmt.Println("---------------------")
    		tx.DescendRange("last_name", `{"name":{"last":""}}`, `{"name":{"last":"Ma"}}`, func(key, value string) bool {
    			fmt.Printf("%s: %s\n", key, value)
    			return true
    		})
    		return nil
    	})
    

    result:

    ---------------------
    2: {"name":{"first":"Janet","last":"Prichard"},"age":"47"}
    7: {"name":{"first":"Pony","last":"Ma"},"age":"3"}
    5: {"name":{"first":"Jack","last":"Ma"},"age":"20"}
    9: {"name":{"first":"Larry","last":"Liu"},"age":""}
    8: {"name":{"first":"Robin","last":"Li"},"age":"2"}
    6: {"name":{"first":"Blues","last":"Li"},"age":"31"}
    1: {"name":{"first":"Tom","last":"Johnson"},"age":"38"}
    4: {"name":{"first":"Alan","last":"Cooper"},"age":"28"}
    3: {"name":{"first":"Carol","last":"Anderson"},"age":"52"}
    ---------------------
    

    tx.CreateIndex("last_name", "*", buntdb.IndexJSON("name.last") replace tx.CreateIndex("last_name", "*", buntdb.Desc(buntdb.IndexJSON("name.last")))

    result:

    ---------------------
    3: {"name":{"first":"Carol","last":"Anderson"},"age":"52"}
    4: {"name":{"first":"Alan","last":"Cooper"},"age":"28"}
    1: {"name":{"first":"Tom","last":"Johnson"},"age":"38"}
    8: {"name":{"first":"Robin","last":"Li"},"age":"2"}
    6: {"name":{"first":"Blues","last":"Li"},"age":"31"}
    9: {"name":{"first":"Larry","last":"Liu"},"age":""}
    7: {"name":{"first":"Pony","last":"Ma"},"age":"3"}
    5: {"name":{"first":"Jack","last":"Ma"},"age":"20"}
    2: {"name":{"first":"Janet","last":"Prichard"},"age":"47"}
    ---------------------
    3: {"name":{"first":"Carol","last":"Anderson"},"age":"52"}
    4: {"name":{"first":"Alan","last":"Cooper"},"age":"28"}
    1: {"name":{"first":"Tom","last":"Johnson"},"age":"38"}
    8: {"name":{"first":"Robin","last":"Li"},"age":"2"}
    6: {"name":{"first":"Blues","last":"Li"},"age":"31"}
    9: {"name":{"first":"Larry","last":"Liu"},"age":""}
    
    
  • Is it in-memory db?

    Is it in-memory db?

    I worked with boltdb,it's like Buntdb. As mentioned in Documentation buntdb is an in-memory database(while boltdb isn't). So can it manage write(on-disk) operation faster than disk memory DBs?(Does it use any in-memory middle cache and write queue?)

  • How to renew the ttl?

    How to renew the ttl?

    from the source code right now the only way to renew an existing key-value entry ttl is to call *Set(key, value string, opts SetOptions) again.

    suggest to add a new method as below : *SetTTL(key string, opts SetOptions)

    for the case just want to update the ttl, the suggested way will gain better performance or not?

  • I wonder if we can find closest lat long for a given latlon from spatial index using nearby

    I wonder if we can find closest lat long for a given latlon from spatial index using nearby

    This is more of a question, We need to use haversine distance algorithm while indexing as well as searching?, is it possible to search closest lat long points ?

  • Question: What is the format of .db file?

    Question: What is the format of .db file?

    • How to generate .db file?
    • What means $3, *3 and so on..?
    *3
    $3
    set
    $35
    account.lastseen danieliamanadminus
    $635
    {"":"2021-03-12T19:02:23.967591811Z","AdfdDfdsaSds":"2021-03-12T15:29:07.517666927Z","someoneAnywayLol":"2021-01-10T14:59:37.444691184Z","aliceo":"2021-01-10T10:32:25.489426821Z","koryCaccoAccountUwu":"2021-02-13T19:41:14.449738789Z","dananan":"2021-01-21T07:16:31.289440487Z","danantheman":"2021-01-03T12:19:36.737684151Z","MarioHey":"2021-01-13T07:49:24.638691227Z","MarMarMarMarioioioioi":"2021-03-12T14:06:04.567924428Z","ackYesIGotItYaBastardi":"2021-03-12T19:27:37.905129873Z","thisiseomth":"2021-02-03T07:48:35.702562025Z","anotheruserhere":"2021-01-23T10:01:09.970222719Z","mariomaybeidunnowh":"2021-02-24T15:29:32.572548859Z"}
    

    example from Issue #72

  • tx.Ascend doesn't work correctly

    tx.Ascend doesn't work correctly

    when I store keys todo:0000000001 until todo:0000000010 (so 10 different records) I see the order being right.

    if I store todo:0000000001 again after that, the order is broken, because that last "record" is presented last, while the documentation states: All keys/value pairs are ordered in the database by the key. To iterate over the keys:

    Extra info: I have created an index on todo:

    	err = db.CreateIndex("todo", "todo:*", buntdb.IndexString)
    	if err != nil && err.Error() != "index exists" {
    		log.Println(strings.ReplaceAll(fmt.Sprintf(`save.go:97 err %#v`, err), `, `, ",\n"))
    	}
    

    The insert goes like this:

    	err = db.Update(func(tx *buntdb.Tx) error {
    		fmt.Println(`save key:`, dbkey)
    		_, _, err = tx.Set(dbkey, val, nil)
    
    		return err
    	})
    
    

    Result:

    save key: todo:0000000001
    save key: todo:0000000002
    save key: todo:0000000003
    save key: todo:0000000004
    save key: todo:0000000005
    save key: todo:0000000006
    save key: todo:0000000007
    save key: todo:0000000008
    save key: todo:0000000009
    save key: todo:0000000010
    save key: todo:0000000001
    

    I get all of my todos:

    err = db.View(
    		func(tx *buntdb.Tx) error {
    			err := tx.Ascend("todo", func(key, value string) bool {
    				fmt.Printf("ascend key: %s\n", key)
    				return true // continue iteration
    			})
    
    			return err
    		})
    

    Result:

    ascend key: todo:0000000002
    ascend key: todo:0000000003
    ascend key: todo:0000000004
    ascend key: todo:0000000005
    ascend key: todo:0000000006
    ascend key: todo:0000000007
    ascend key: todo:0000000008
    ascend key: todo:0000000009
    ascend key: todo:0000000010
    ascend key: todo:0000000001
    

    Am I doing something wrong?

    I tried to do it with:

    	err = db.CreateIndex(todoBucket, todoBucket+":*", buntdb.IndexInt)
    

    and that works. But how come the indexString doesn't work? In my book the order should be the same because of the leading zeros, right?

  • index, or getting with different keys doesn't work

    index, or getting with different keys doesn't work

    I have an index on "todo" and an index on "other" I have key "todo:00001" and a key "other:00001" when I save them and try to get only the "todo" ones (ascend the "todo" index) no record is found when I ascend the "other" index, I find the 2 records.

    package main
    
    import (
    	"fmt"
    	"log"
    	"strings"
    
    	"github.com/tidwall/buntdb"
    )
    
    const (
    	todoBucket  = "todo"
    	otherBucket = "other"
    )
    
    func main() {
    	// Open the data.db file. It will be created if it doesn't exist.
    	db, err := buntdb.Open("buntData.db")
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	err = db.CreateIndex(todoBucket, todoBucket+":*", buntdb.IndexString)
    	if err != nil && err.Error() != "index exists" {
    		log.Println(strings.ReplaceAll(fmt.Sprintf(`save.go:97 err %#v`, err), `, `, ",\n"))
    	}
    
    	err = db.CreateIndex(otherBucket, otherBucket+":*", buntdb.IndexString)
    	if err != nil && err.Error() != "index exists" {
    		log.Println(strings.ReplaceAll(fmt.Sprintf(`save.go:97 err %#v`, err), `, `, ",\n"))
    	}
    
    	key := "0000000001"
    	err = save(db, todoBucket, key)
    	if err != nil {
    		log.Println(strings.ReplaceAll(fmt.Sprintf(`save.go:107 err %#v`, err), `, `, ",\n"))
    	}
    
    	err = save(db, otherBucket, key)
    	if err != nil {
    		log.Println(strings.ReplaceAll(fmt.Sprintf(`save.go:107 err %#v`, err), `, `, ",\n"))
    	}
    
    	showAll(db, todoBucket)
    	showAll(db, otherBucket)
    
    	defer db.Close()
    }
    
    func save(db *buntdb.DB, bucket, key string) error {
    	var err error
    	dbkey := fmt.Sprintf("%s:%s", bucket, key)
    	val := "val of key " + dbkey
    
    	err = db.Update(func(tx *buntdb.Tx) error {
    		log.Println(`save.go:103 key:`, dbkey)
    
    		_, _, err = tx.Set(dbkey, val, nil)
    
    		return err
    	})
    
    	return err
    }
    
    func showAll(db *buntdb.DB, bucket string) {
    	var err error
    	println("SHOWALL: " + bucket)
    
    	err = db.View(
    		func(tx *buntdb.Tx) error {
    			err := tx.Ascend(bucket, func(key, value string) bool {
    				fmt.Printf("key: %s, value: %s\n", key, value)
    				return true // continue iteration
    			})
    
    			return err
    		})
    
    	log.Println(strings.ReplaceAll(fmt.Sprintf(`get.go:60 err %#v`, err), `, `, ",\n"))
    }
    
    
BadgerDB is an embeddable, persistent and fast key-value (KV) database written in pure Go
BadgerDB is an embeddable, persistent and fast key-value (KV) database written in pure Go

BadgerDB BadgerDB is an embeddable, persistent and fast key-value (KV) database written in pure Go. It is the underlying database for Dgraph, a fast,

Dec 10, 2021
pure golang key database support key have value. 非常高效实用的键值数据库。
pure golang key database support key have value.  非常高效实用的键值数据库。

orderfile32 pure golang key database support key have value The orderfile32 is standard alone fast key value database. It have two version. one is thi

Apr 30, 2022
A simple, fast, embeddable, persistent key/value store written in pure Go. It supports fully serializable transactions and many data structures such as list, set, sorted set.

NutsDB English | 简体中文 NutsDB is a simple, fast, embeddable and persistent key/value store written in pure Go. It supports fully serializable transacti

Jan 1, 2023
Membin is an in-memory database that can be stored on disk. Data model smiliar to key-value but values store as JSON byte array.

Membin Docs | Contributing | License What is Membin? The Membin database system is in-memory database smiliar to key-value databases, target to effici

Jun 3, 2021
Simple key value database that use json files to store the database

KValDB Simple key value database that use json files to store the database, the key and the respective value. This simple database have two gRPC metho

Nov 13, 2021
Distributed cache and in-memory key/value data store.

Distributed cache and in-memory key/value data store. It can be used both as an embedded Go library and as a language-independent service.

Dec 30, 2022
An in-memory key:value store/cache (similar to Memcached) library for Go, suitable for single-machine applications.

go-cache go-cache is an in-memory key:value store/cache similar to memcached that is suitable for applications running on a single machine. Its major

Dec 29, 2022
A minimalistic in-memory key value store.
A minimalistic in-memory key value store.

A minimalistic in-memory key value store. Overview You can think of Kiwi as thread safe global variables. This kind of library comes in helpful when y

Dec 6, 2021
A rest-api that works with golang as an in-memory key value store

Rest API Service in GOLANG A rest-api that works with golang as an in-memory key value store Usage Run command below in terminal in project directory.

Dec 6, 2021
Real-time Geospatial and Geofencing
Real-time Geospatial and Geofencing

Tile38 is an open source (MIT licensed), in-memory geolocation data store, spatial index, and realtime geofence. It supports a variety of object types

Dec 30, 2022
ArcticDB - an embeddable columnar database written in Go
ArcticDB - an embeddable columnar database written in Go

This project is still in its infancy, consider it not production-ready, probably has various consistency and correctness problems and all API will cha

Dec 29, 2022
An embedded key/value database for Go.

bbolt bbolt is a fork of Ben Johnson's Bolt key/value store. The purpose of this fork is to provide the Go community with an active maintenance and de

Jan 1, 2023
ACID key-value database.

Coffer Simply ACID* key-value database. At the medium or even low latency it tries to provide greater throughput without losing the ACID properties of

Dec 7, 2022
LevelDB key/value database in Go.

This is an implementation of the LevelDB key/value database in the Go programming language. Installation go get github.com/syndtr/goleveldb/leveldb R

Jan 1, 2023
Graviton Database: ZFS for key-value stores.
Graviton Database: ZFS for key-value stores.

Graviton Database: ZFS for key-value stores. Graviton Database is simple, fast, versioned, authenticated, embeddable key-value store database in pure

Dec 31, 2022
An embedded, hardened key/value database for Go.

Bolt Bolt is a pure Go key/value store inspired by Howard Chu's LMDB project. The goal of the project is to provide a simple, fast, and reliable datab

Nov 4, 2021
GalaxyDB is a hobbyist key-value database written in Go.

GalaxyDB GalaxyDB is a hobbyist key-value database written in Go Author: Andrew N ([email protected]) Features Data is stored via keys Operations Grafana

Mar 30, 2022
🔑A high performance Key/Value store written in Go with a predictable read/write performance and high throughput. Uses a Bitcask on-disk layout (LSM+WAL) similar to Riak.

bitcask A high performance Key/Value store written in Go with a predictable read/write performance and high throughput. Uses a Bitcask on-disk layout

Sep 26, 2022
Fast and simple key/value store written using Go's standard library
Fast and simple key/value store written using Go's standard library

Table of Contents Description Usage Cookbook Disadvantages Motivation Benchmarks Test 1 Test 4 Description Package pudge is a fast and simple key/valu

Nov 17, 2022