I have problem with the term query in elasticsearch. I send the following query:
{
"query": {
"term": {
"title":"Test1"
}
}
}
I have an empty result:
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 3,
"successful": 3,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 0,
"max_score": null,
"hits": []
}
}
But if I send the following:
{
"query": {
"term": {
"root":true
}
}
}
I have:
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 3,
"successful": 3,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 3,
"max_score": 0.2876821,
"hits": [
{
"_index": "content_2018-05-30-092148",
"_type": "topic",
"_id": "6064f7ac-63d5-11e8-adc0-fa7ae01bbeb1",
"_score": 0.2876821,
"_source": {
"_meta": {
"model": "Secafi\\Content\\Topic"
},
"id": "6064f7ac-63d5-11e8-adc0-fa7ae01bbeb1",
"title": "Test2",
"root": true
}
},
{
"_index": "content_2018-05-30-092148",
"_type": "topic",
"_id": "6064f7ac-63d5-11e8-adc0-fa7ae01bbeb2",
"_score": 0.2876821,
"_source": {
"_meta": {
"model": "Secafi\\Content\\Topic"
},
"id": "6064f7ac-63d5-11e8-adc0-fa7ae01bbeb2",
"title": "Test3",
"root": true
}
},
{
"_index": "content_2018-05-30-092148",
"_type": "topic",
"_id": "6064f7ac-63d5-11e8-adc0-fa7ae01bbebc",
"_score": 0.2876821,
"_source": {
"_meta": {
"model": "Secafi\\Content\\Topic"
},
"id": "6064f7ac-63d5-11e8-adc0-fa7ae01bbebc",
"title": "Test1",
"root": true
}
}
]
}
}
I have the same result if I do a match query on the title field, it never returns any document.
What's wrong. Why the first query doesn't return the document Test1?
The term query looks for the exact term. Is likely that you are using the standard analyzer which has the lowercase filter. So you are searching for exactly "Term1" when what is in the index is "term1".
Term is great for things like exact match numbers or ids (like 9844-9332-22333). Less so for a fields like titles of posts.
To confirm this you could do:
{
"query": {
"term": {
"title.keyword":"Test1"
}
}
}
Which should work if your record is indexed with the exact title of "Test1". This uses the keyword analyzer instead of the standard analyzer (notice the ".keyword" after title). In the latest versions of elasticsearch the keyword analyzer is added by default unless you override this behavior. Keyword is an exact match "noop" analyzer that returns the entire string as a single token to match against.
For a title, what you probably want is:
{
"query": {
"match": {
"title":"Test1"
}
}
}
Match query runs your input string through the standard analyzer that was used by default to index the document (lowercaseing etc) so elasticsearch is able to match your query text to what is in the elasticsearch index.
Checkout the docs for more details on match vs term. https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html