Reputation: 13
Suppose there are 3 documents :
{
"id": 1
"recipe": "egg apple peach"
}
{
"id": 2
"recipe": "egg apple"
}
{
"id": 3
"recipe": "egg apple potato"
}
I want to lookup such that if all the words of the recipe
field of the document are present in my search query.
So the query : "egg apple peach"
should return the documents 1 and 2.
The query : "egg apple"
should return the documents 2.
How can I provide this kind of query with Elasticsearch ?
Upvotes: 1
Views: 263
Reputation: 9109
Returns documents that contain a minimum number of exact terms in a provided field
This can be used to return documents when query contains minimum number of token present in document. First you need to index document with token_count data type.
A field of type token_count is really an integer field which accepts string values, analyzes them, then indexes the number of tokens in the string.
In index we will store number of token for recipe.
Example :
For "recipe": "egg apple potato" recipe.length=3
For "recipe": "egg apple" recipe.length=2
Mapping:
PUT index12
{
"mappings": {
"properties": {
"id":{
"type": "integer"
},
"recipe":{
"type": "text",
"fields": {
"length":{
"type":"token_count",
"analyzer":"standard"
}
}
}
}
}
}
Query:
{
"query": {
"terms_set": {
"recipe": {
"terms": [
"egg",
"apple",
"peach"
],
"minimum_should_match_script": {
"source": """ if(doc['recipe.length'].size()==0) return 0; else return doc['recipe.length'].value"""
}
}
}
}
}
Result:
"hits" : [
{
"_index" : "index12",
"_type" : "_doc",
"_id" : "Wj563XEBly0sCU1FGf2v",
"_score" : 1.1871837,
"_source" : {
"id" : 1,
"recipe" : "egg apple peach"
}
},
{
"_index" : "index12",
"_type" : "_doc",
"_id" : "Wz563XEBly0sCU1FIf06",
"_score" : 0.29748765,
"_source" : {
"id" : 2,
"recipe" : "egg apple"
}
}
]
Upvotes: 0