TheJediCowboy
TheJediCowboy

Reputation: 9222

ElasticSearch MultiField Search Query

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

/users?nickname=myUsername&[email protected]&name=John+Smith

Somet details about these parameters are the following

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
});

Upvotes: 0

Views: 1031

Answers (1)

Vineeth Mohan
Vineeth Mohan

Reputation: 19253

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": "[email protected]"
          }
        }
      ]
    }
  }
}

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

Upvotes: 6

Related Questions