Nibor
Nibor

Reputation: 679

Cloudant search document by attributes of nested objects

My documents in cloudant have the following structure

{
 "_id"      : "1234",
 "name"     : "test",
 "objects"  : [
   {
     "type"  :  "TYPE1"
     "time"  :  "1215
   },
   {
     "type"  :  "TYPE2"
     "time"  :  "1115"
   }
 ]
}

Now I need to query my documents by a list of types.

Examples

1) If I would query with TYPE1 then all the documents where there is an object with this type would return. (The example doc would return)

2) If I would query with TYPE1 and TYPE3 it would return all documents which contain either of them (The example doc would return)

3) If I would query with TYPE3, TYPE4 and TYPE5 it would return all documents which contain either of them (The example doc would not return)

How would the code in the _design document look like and how would my API request look like?

Upvotes: 1

Views: 899

Answers (1)

ptitzler
ptitzler

Reputation: 923

One option is to use Cloudant Search.

Sample design document named types, which indexes each type property in your objects array

{
 "_id": "_design/types",
 "views": {},
 "language": "javascript",
 "indexes": {
  "one-of": {
   "analyzer": "standard",
   "index": "function (doc) {\n  for(var i in doc.objects) {\n    index(\"type\", doc.objects[i].type);  \n  }\n}"
  }
 }
}

Query examples:

Search for one key (type=val)

GET https://$HOST/$DATABASE/_design/$DDOC/_search/one-of?q=type%3ATYPE1

Search for multiple keys (type=val1 OR type=val2)

GET https://$HOST/$DATABASE/_design/$DDOC/_search/one-of?q=type%3ATYPE1%20OR%20type%3ATYPE2

Search for multiple keys (type=val1 AND type=val2)

GET https://$HOST/$DATABASE/_design/$DDOC/_search/one-of?q=type%3ATYPE1%20AND%20type%3ATYPE2

To include the documents in the response append &include_docs=true.

Upvotes: 4

Related Questions