0

I have an endpoint that I am proxying into ElasticSearch API for a simple user search I am conducting.

/users?nickname=myUsername&email=myemail@gmail.com&name=John+Smith

Somet details about these parameters are the following

  • All parameters are optional
  • nickname can be searched as a full text search (i.e. 'myUser' would return 'myUsername')
  • email must be an exact match
  • name can be searched as full text search for each token (i.e. 'john' would return 'John Smith')

The ElasticSearch search call should treat the parameters collectively as AND'd.

Right now, I am not truly sure where to start as I am able to execute the query on each of the parameters alone, but not all together.

client.search({
    index: 'users',
    type: 'user',
    body: {
        "query": {
            //NEED TO FILL THIS IN
        }
    }
}).then(function(resp){
    //Do something with search results
});
TheJediCowboy
  • 8,924
  • 28
  • 136
  • 208

1 Answers1

6

First you need to create the mapping for this particular use case.

curl -X PUT "http://$hostname:9200/myindex/mytype/_mapping" -d '{
  "mytype": {
    "properties": {
      "email": {
        "type": "string",
        "index": "not_analyzed"
      },
      "nickname": {
        "type": "string"
      },
      "name": {
        "type": "string"
      }
    }
  }
}'

Here by making email as not_analyzed , you are making sure only the exact match works. Once that is done , you need to make the query. As we have multiple conditions , it would be a good idea to use bool query. You can combine multiple queries and how to handle them using bool query

Query -

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "name": "qbox"
          }
        },
        {
          "prefix": {
            "nickname": "qbo"
          }
        },
        {
          "match": {
            "email": "me@qbox.io"
          }
        }
      ]
    }
  }
}

Using the prefix query , you are telling Elasticsearch that even if the token starts with qbo , qualify it as a match.

Also prefix query might not be very fast , in that case you can go for ngram analyzer - http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/analysis-ngram-tokenizer.html

Andrei Stefan
  • 51,654
  • 6
  • 98
  • 89
Vineeth Mohan
  • 18,633
  • 8
  • 63
  • 77