Vítor Marçal
Vítor Marçal

Reputation: 775

ElasticSearch Query does not return exact string

How to make the query to return only "Projeto de Lei"? Currently the query returns "Projeto de Lei" and various records such as "Projeto de Lei X", "Projeto de Lei Y", "Projeto de Lei XYZ" etc etc.

  {
    "query" : {
       "query_string" : { 
          "query" : "descricaoProposicao:Projeto+de+Lei", "default_operator": "AND"
        }
     }
   }

Upvotes: 0

Views: 139

Answers (1)

Kamal Kunjapur
Kamal Kunjapur

Reputation: 8860

There are ways to do this:

Using Analyzer

What you need is to make use of correct Analyzer for your field. Elasticsearch by default uses Standard Analyzer and if you would like to store the entire string as it, you need to make sure that you use Keyword Analyzer.

And then you can make use of simple match query for this.

POST <your_index_name>/_search
{
  "query": {
    "match": {
      "your_field_name": "Projeto de Lei" 
    }
  }
}

Using Term Query

Alternatively, Elasticsearch provides you a datatype keyword which in turn makes use of keyword analyzer.

You can then make use of Term Query. The link I've mentioned has good information on this.

Basically your query would be in below form and your_field_name is of type keyword

POST <your_index_name>/_search
{
  "query": {
    "term": {
      "your_field_name": "Projeto de Lei" 
    }
  }
}

Well, you can also make use of match or match_phrase but make sure you use it on field having type as keyword for exact match.

POST <your_index_name>/_search
{
  "query": {
    "match_phrase": {
      "your_field_name": "Projeto de Lei" 
    }
  }
}

What I'd recommend is to have Multi-Field created for the field on which you are querying.

In that way, you can do both keyword (exact) search using Term Query(recommended approach for exact match) for this and on the text field you can do simple text based search (would return results what you are currently observing).

Hope it helps!

Upvotes: 1

Related Questions