1

Hi how to create index on array field my sample doc is

   { 
"name": [     {
      "family": "Smith",
      "given": [
        "Kam"
      ],
      "prefix": [
        "Mrs."
      ],
      "use": "official"
    },
    {
      "family": "Johns",
      "given": [
        "Kam"
      ],
      "use": "maiden"
    }
  ]
}

I want to write a search query (like) on family and given fields ...How to create a index and suggest query ..Im new to couchbase

1
  • Is this for Couchbase or Couchbase Lite? Commented Jun 21, 2018 at 21:45

1 Answer 1

2

This query that selects the customers with family name "Smith" and given name "Kam":

select * from customer
where any n in name satisfies n.family = 'Smith' and 
          any fn in n.given satisfies fn = 'Kam' end end

Note the use of a nested ANY clause because of the use of a nested array in the data.

You can then create an index on the family name like this:

CREATE INDEX customer_name ON customer
   ( DISTINCT ARRAY n.family FOR n IN name END)

The index gets used without any hints. You can see that it is being used by adding EXPLAIN to the beginning of the query. That will get you a query plan in JSON that includes an index scan operator.

You can learn more about array indexing here: https://developer.couchbase.com/documentation/server/current/n1ql/n1ql-language-reference/indexing-arrays.html

Sign up to request clarification or add additional context in comments.

1 Comment

not sure if it will scan the entire index, or if it will know how to apply a start-stop key. Sounds like it will have to scan all entries in the index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.