lucenewildcardcloudantpython-cloudant

Cloudant: How to perform wildcard searches on text fields


I have a db in cloudant that looks like this

count word

4     a         
1     a boy
1     a boy goes

i want to run a query like this

word: *boy*

how do i do this in cloudant? i tried the following but it did not work

{
  "selector": {
    "word": "*boy*"
  },
  "fields": [

  ],
  "sort": [
    {
      "_id": "asc"
    }
  ]
}

Solution

  • You could use the $regexcondition operator.

    {
     "selector": {
       "word": {
        "$regex": "boy"
       }
     },
     "fields": [
     ],
     "sort": [
      {
       "_id": "asc"
      }
     ]
    }
    

    From the doc:

    A regular expression pattern to match against the document field. Only matches when the field is a string value and matches the supplied regular expression.

    Because regular expressions do not work with indexes you should consider using Cloudant Search instead of Cloudant Query if your data set is rather large.

    Create a design document that defines an index on the word document property:

    {
     "_id": "_design/search_example",
     "indexes": {
       "word": {
        "index": "function(doc){if (doc.word) {index('word', doc.word, {'store': true});}}"
      }
     }
    }
    

    Run search:

    GET https://$HOST/$DATABASE/_design/search_example/_search/word?q=word:boy HTTP/1.1
    

    The result will include all documents that contain the specified string in the word document property. To return the documents use ?q=word:boy&include_docs=true

    Hope this helps!