1

How could I query a levelDB database by values in nodejs? I have key: value pairs in my leveldb database and I want to search some values in it and find that key-value pair from that result. I am a beginner in leveldb.

{
    "key1" : {
                 "data1": "value1",
                 "data2": "value2",
                 "data3": "value3"
             }
}

So, I want to query value where data3 == value3 and get that key-value pair.

In levelDB, we can only get data on the basis of key. Is there any other alternative?

shubgpt
  • 15
  • 1
  • 3
  • I found one alternative to it by using levelgraph, in which we can search data using subject, predicate and object. But still if one have a object in any of these then searching those keys or values will be difficult. – shubgpt Jul 11 '18 at 08:02

1 Answers1

2

In leveldb, which a low level database abstraction you can "only" query by exact key match or prefix key range.

You can not query by value without somekind duplication.

What pattern I adopted in my graphdb project is to follow the EAV model with a secondary "table" to store the index.

In Python plyvel you can emulate "table" using prefixed databases. Or see how FoundationDB does it in its Subspace implementation. Basically, every key-value pair of a given "table" or "space" is prefixed with a particular bytes sequence, that is all.

The first table, looks like the following:

(Entity, Attribute) → (Value)

Where Entity is a (random) identifier and Attribute is the byte representation of field name and last but not least Value is the bytes serialized value associated with Attribute for the given Entity.

The table schema is done that way so that you can quickly fetch using a range query all Attribute and Value using prefix range search over a given Entity.

The index table use the following schema:

(Attribute, Value) → Entity

That is it a shuffled version of the first table.

This is done like so, to make it possible to quickly fetch Entity that match a particular Attribute == Value that's what you are looking for.

There is alternative implementations for what you are looking for. Lookup my answers about leveldb and key-value stores e.g. Expressing multiple columns in berkeley db in python?

Good luck!

amirouche
  • 7,682
  • 6
  • 40
  • 94
  • Thanks for the answer! By your explanation, I am able to create a small database but now I was thinking what if I have to query nested value. I am trying to create a blockchain type solution in nodejs. – shubgpt Jul 18 '18 at 13:29
  • I don't know blockchain. That said, if you want to create an `Entity` and use as `Value` of another entity. That way one entity contains another somewhat. – amirouche Jul 20 '18 at 10:56