Search code examples
couchdbcloudant

How would I query keys such that it would partially match?


Let's take this document for example:

{
"id":1
"planet":"earth-616"
"data":[
    ["wolverine","mutant"],
    ["Storm","mutant"],
    ["Mark Zuckerberg","human"]]
}

I created a search index to index the name and type, for example if searched for name:wolverine or type:mutant I'd get the document that has it. But as per my requirement I don't want the whole document, I only want ["wolverine","mutant"] I've created a view that outputs as:

{
    "id":1,
    "key":"earth-616",
    "value":["earth-616","wolverine","mutant"]
}

Then I found out I can query only with keys. (Is it possible to create search indexes on views?, Couldn't find anything in the documentation) Or should I create views along with the one above like this:

{
    "id":1,
    "key":"wolverine",
    "value":["earth-616","wolverine","mutant"]
}

And

{
    "id":,
    "key":"mutant"
    "value":["earth-616","wolverine","mutant"]
}

This way I can query with keys that I want but I can't seem to partial match keys(Am I missing something?)


Solution

  • If you need the output to be exactly as described then I believe you have to use views, and to support wildcard searches I believe you will have to index every substring of a key.

    One alternative is to use Cloudant Query, although admittedly you cannot get the exact output you are looking for. If you issue a query like so:

    {
      "selector": {
        "_id": {
          "$gt": 0
        },
        "data": {
          "$elemMatch": {
            "$elemMatch": {
              "$regex": "(?i)zuck"
            }
          }
        }
      },
      "fields": [
        "data"
      ]
    }
    

    The result will be the entire data array:

    {
      "data": [
        ["wolverine", "mutant"],
        ["Storm", "mutant"],
        ["Mark Zuckerberg", "human"]
      ]
    }