Luca Mastrostefano
Luca Mastrostefano

Reputation: 3281

How do I specify a different analyzer at query time with Elasticsearch?

I would like to use a different analyzer at query time to compose my query.

I read that is possible from the documentation "Controlling Analysis" :

[...] the full sequence at search time:

  • The analyzer defined in the query itself, else
  • The search_analyzer defined in the field mapping, else
  • The analyzer defined in the field mapping, else
  • The analyzer named default_search in the index settings, which defaults to
  • The analyzer named default in the index settings, which defaults to
  • The standard analyzer

But i don't know how to compose the query in order to specify different analyzers for different clauses:

"query"  => [
    "bool" => [
        "must"   => [
            {
                "match": ["my_field": "My query"]
                "<ANALYZER>": <ANALYZER_1>
            }
        ],
        "should" => [
            {
                "match": ["my_field": "My query"]
                "<ANALYZER>": <ANALYZER_2>    
            }
        ]
    ]
]

I know that i can index two or more different fields, but I have strong secondary memory constraints and I can't index the same information N times.

Thank you

Upvotes: 8

Views: 6812

Answers (1)

corin123
corin123

Reputation: 146

If you haven't yet, you first need to map the custom analyzers to your index settings endpoint.

Note: if the index exists and is running, make sure to close it first.

POST /my_index/_close

Then map the custom analyzers to the settings endpoint.

PUT /my_index/_settings
{
  "settings": {
    "analysis": {
      "analyzer": {
        "custom_analyzer1": { 
          "type": "standard",
          "stopwords_path": "stopwords/stopwords.txt"
        },
        "custom_analyzer2": { 
          "type": "standard",
          "stopwords": ["stop", "words"]
        }
      }
    }
  }
}

Open the index again.

POST /my_index/_open

Now you can query your index with the new analyzers.

GET /my_index/_search
{
  "query": {
    "bool": {
      "should": [{
        "match": {
          "field_1": {
            "query": "Hello world",
            "analyzer": "custom_analyzer1"
          }
        }
      }],
      "must": [{
        "match": {
          "field_2": {
            "query": "Stop words can be tough",
            "analyzer": "custom_analyzer2"
          }
        }
      }]
    }
  }
}

Upvotes: 13

Related Questions