Let say, I have field name “id”, “nm” “limit”, “description”, “la”
All fields are of multi field, where main field is of TEXT and KEYWORD has suffix as “ke”. And normalizer for lower case is implemented on KEYWORD field type.
Now requirement is, I have to provide a search feature on “nm”. If user search a text string then exact words in string should take priority and display first. Resultset should also have data for words where anyone of words from search string is available even if partial word.
Example :
Dataset:
- Hello I am Rishabh Kabra
- Wow! I am using Elasticsearch
- Hey… Are you here?
- Let’s work on function youth
Example 1 :
Search String : wow! I am
Expected result :
- Wow! I am using Elasticsearch
- Hello I am Rishabh Kabra
- Let’s work on function youth
Explanation : 1. Will take priority as it has exact search string “wow! I am”
2. It will come on second priority as it has partial exact string “I am”
3. Least priority but in Resultset because of partial word functionality as it has “i” from search string.
Example 2:
Search String : Are you
Expected result :
- Hey… Are you here?
- Let’s work on function youth
Explanation :
- Will take priority as it has exact partial search “are you” string
- Will come in result as it has partial word “you” in “youth”
I need elastic query for this requirement.
I have tried function_score with boost but it is not working for special characters. I have made combination of exact word search with wildcard, that one work sometime and sometime not
try this query. This should resolve your issue
{
"query": {
"bool": {
"must": [
{
"function_score": {
"query": {
"bool": {
"should": [
{
"term": {
"nm.ke": {
"value": "wow! i am", // Exact match on "nm"
"boost": 5
}
}
},
{
"match_phrase": {
"nm": {
"query": "wow! i am",
"boost": 3
}
}
},
{
"multi_match": {
"query": "wow! i am",
"fields": ["nm"],
"type": "phrase_prefix",
"boost": 2
}
},
{
"multi_match": {
"query": "wow! i am",
"fields": ["nm"],
"type": "best_fields",
"fuzziness": "AUTO",
"boost": 1
}
}
]
}
},
"score_mode": "sum" // Combine scores for "nm"
}
},
{
"match": {
"description": {
"query": "simple search", // Query for "description"
"operator": "and"
}
}
},
{
"match": {
"la": {
"query": "some text", // Query for "la"
"operator": "and"
}
}
}
]
}
}
}