user9027927
user9027927

Reputation:

How to find a document using a value to search in a range?

The database is the range of geolocation of IP address and each document look like this;

{
  "_id": "1000013824",
  "_rev": "1-b747bd47d44efe619c9b4f8d867131ad",
  "f": "1000079359",
  "p": "CN"
}

I created a view to make the output like this:

"total_rows":202238,"offset":0,"rows":[
{"id":"0","key":["0","16777215"],"value":"ZZ"},
{"id":"1000013824","key":["1000013824","1000079359"],"value":"CN"},
{"id":"1000079360","key":["1000079360","1000083455"],"value":"JP"},
{"id":"1000083456","key":["1000083456","1000084479"],"value":"JP"},

But I am unable to search a value, for example, 1000013825 which is the first document but the value does not correspond to a startkey or endkey. How can I do this? Using JS and the data in a array, I could do this:

        return array.find(doc=> {
                if (doc._id <= this && doc.f >= this) {
                    return doc.p;
                }
            };

But I do not have a clue how to do it in CouchDB 2.3.1.

Upvotes: 0

Views: 192

Answers (1)

uminder
uminder

Reputation: 26150

Assuming you're using the CouchDB Core API, you could query the dodument from the database (not the view) by the use of POST /{db}/_find and the following request body:

{
    "selector": {
        "f": {"$gte": value }
    },
    "fields": ["f", "p"],
    "sort":[ 
        {"f": "asc"}
    ],
    "limit": 1
}

Please note that an index must previously be created for the sort field f (see /db/_index).

Upvotes: 0

Related Questions