Frank Santillan
Frank Santillan

Reputation: 27

Searching many parameters in a Cloudant noSQL DB

I am using a Cloudant database on Bluemix to storage products in a Node.js server. These products will be searched by categories. To find a product that has only one category, would not be a problem because a search is made by comparing the string that is sent as a search parameter with the category string that is saved in the database. The problem occurs when a product has two or more categories. At the time of making the comparison of string to string, it would never coincide.

The products can have as many categories as they need.

Any ideas?

Upvotes: 1

Views: 181

Answers (2)

Rafael Gallardo
Rafael Gallardo

Reputation: 143

You should store one or more categories in array format in Cloudant database in "category" parameter

{
  "_id": "producto1",
  "category: ["TV", "cameras", "computers"]
}

Then you should create a search index

function (doc) {
  if (doc.category) {
    for (var i in doc.category) {
      index("category", doc.category[i], {"store": true, "facet": true})
    }
  }
}

Now you can query the documents from Cloudant Query

{
  "selector": {
    "_id": {
      "$gt": 0
    },
    "category": {
      "$all": [
        "TV",
        "cameras"
      ]
    }
  },
  "fields": [
    "_id",
    "_rev"
  ],
  "sort": [
    {
      "_id": "asc"
    }
  ]
}

Or you can use

https://{url_database}/{name_database}/_design/{name_design}/_search/{name_search}?q=category:TV

Upvotes: 1

vabarbosa
vabarbosa

Reputation: 706

if i am understanding your question correctly, you may want to store category as an array of strings and index each element in the array. you can then search products against a single or multiple categories.

for example, given the following documents:

doc 1

{
  "name": "product1",
  "category: ["abc"]
}

doc 2

{
  "name": "product2",
  "category: ["abc", "def"]
}

you can set up a search index similar to:

function (doc) {
  if (doc.category) {
    for (var i in doc.category) {
      index("category", doc.category[i], {"store": true, "facet": true})
    }
  }
}

then you may run queries like such:

.../{dbname}/_design/{designdocname}/_search/{searchindexname}?q=category:abc

which would return both product1 and product2 or:

.../{dbname}/_design/{designdocname}/_search/{searchindexname}?q=category:abc+AND+category:def

which would return only product2.

additional info: https://developer.ibm.com/clouddataservices/cloudant-search/

Upvotes: 1

Related Questions