0

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.

1 Answers1

0

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).

uminder
  • 23,831
  • 5
  • 37
  • 72
  • Just to update the link for the /db/_index: https://docs.couchdb.org/en/2.3.1/api/database/find.html#db-index –  Dec 17 '19 at 09:45
  • I am making: curl -X POST http://127.0.0.1:5984/fneon_paisip -d '{"selector":{"f":{"$gte":"1045150219"}},"fields": ["p"],"sort":[{"f": "asc"}],"limit": 1}' -H "Content-Type: application/json" but it does not return the fields defined in "fields"; only id and rev fields. Also, everytime i make the find, it returns a different id as result. It is not working. Also the ID that returns is completly different from the ones in the database. –  Dec 17 '19 at 09:46
  • I was missing the _find after the name of database: curl -X POST http://127.0.0.1:5984/fneon_paisip/_find -d '{"selector":{"f":{"$gte":"1045150219"}},"fields": ["p"],"sort":[{"f": "asc"}],"limit": 1}' -H "Content-Type: application/json" Now it works. Thank you. –  Dec 17 '19 at 09:56