I put 2 documents in Elasticsearch :
curl -XPUT "http://localhost:9200/vehicles/vehicle/1" -d' { "model": "Classe A" }' curl -XPUT "http://localhost:9200/vehicles/vehicle/2" -d' { "model": "Classe B" }'
Why is this query returns the 2 documents :
curl -XPOST "http://localhost:9200/vehicles/_search" -d' { "query": { "query_string": { "query": "model:\"Classe A\"" } } }'
And this one, only the second document :
curl -XPOST "http://localhost:9200/vehicles/_search" -d' { "query": { "query_string": { "query": "model:\"Classe B\"" } } }'
I want elastic search to match on the exact phrase I pass to the query parameter, WITH the whitespace, how can I do that ?
To search for an exact string, you need to wrap the string in double quotation marks. Without quotation marks, the search in the example would match any documents containing one of the following words: "Cannot" OR "change" OR "the" OR "info" OR "a" OR "user".
After indexing, you can search, sort, and filter complete documents—not rows of columnar data. This is a fundamentally different way of thinking about data and is one of the reasons ElasticSearch can perform a complex full-text search.
Match phrase queryeditA phrase query matches terms up to a configurable slop (which defaults to 0) in any order. Transposed terms have a slop of 2. The analyzer can be set to control which analyzer will perform the analysis process on the text.
What you need to look at is the analyzer you're using. If you don't specify one Elasticsearch will use the Standard Analyzer. It is great for the majority of cases with plain text input, but doesn't work for the use case you mention.
What the standard analyzer will do is split the words in your string and then converts them to lowercase.
If you want to match the whole string "Classe A" and distinguish this from "Classe B", you can use the Keyword Analyzer. This will keep the entire field as one string.
Then you can use the match query which will return the results you expect.
Create the mapping:
PUT vehicles { "mappings": { "vehicle": { "properties": { "model": { "type": "string", "analyzer": "keyword" } } } } }
Perform the query:
POST vehicles/_search { "query": { "match": { "model": "Classe A" } } }
If you wanted to use the query_string
query, then you could set the operator to AND
POST vehicles/vehicle/_search { "query": { "query_string": { "query": "Classe B", "default_operator": "AND" } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With