Search code examples
node.jsdatabaseibm-cloudcloudant

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?


Solution

  • 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/