Reputation: 125
I have a requirement in which I have to sort elastic search data on the basis of fields. For Example, I have some docs indexed in elastic search as shown below.
firstName | lastName | address |
---|---|---|
Lily | Sam | someaddress |
Sam | Adams | anotheraddress |
Michael | Stevens | SamsoniteStreet |
Sort preference should follow the order from higher to lower firstName > lastName > address (firstName has the highest preference and address has the lowest)
So If I search "Sam", results should be returned sorted in this order:
firstName | lastName | address |
---|---|---|
Sam | Adams | anotheraddress |
Lily | Sam | someaddress |
Michael | Stevens | SamsoniteStreet |
Upvotes: 0
Views: 297
Reputation: 16192
You can achieve your use case by boosting per field in the multi_fields
. Adding a working example
Index Mapping:
{
"settings": {
"analysis": {
"analyzer": {
"my_analyzer": {
"tokenizer": "my_tokenizer",
"filter": [
"lowercase"
]
}
},
"tokenizer": {
"my_tokenizer": {
"type": "edge_ngram",
"min_gram": 2,
"max_gram": 20,
"token_chars": [
"letter",
"digit"
]
}
}
},
"max_ngram_diff": 50
},
"mappings": {
"properties": {
"address": {
"type": "text",
"analyzer": "my_analyzer"
},
"firstName": {
"type": "text"
},
"lastName": {
"type": "text"
}
}
}
}
Search Query:
{
"query": {
"multi_match": {
"query": "sam",
"fields": [
"firstName^10",
"lastName^5",
"address"
]
}
}
}
Search Result:
"hits": [
{
"_index": "test",
"_type": "_doc",
"_id": "2",
"_score": 9.808291,
"_source": {
"firstName": "Sam", // note this
"lastName": "Adams",
"address": "anotheraddress"
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "1",
"_score": 4.9041457,
"_source": {
"firstName": "Lily",
"lastName": "Sam", // note this
"address": "someaddress"
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "3",
"_score": 1.8588939,
"_source": {
"firstName": "Michael",
"lastName": "Stevens",
"address": "SamsoniteStreet" // note this
}
}
]
Upvotes: 1