问题
I am facing alphabetical sorting issue in Elastic Search.
I have a Index: indexlive and a "users" type with following mapping:
{
"liveindex": {
"mappings": {
"users": {
"properties": {
"user_Confirmed": {
"type": "boolean"
},
"user_DateOfBirth": {
"type": "text"
},
"user_Email": {
"type": "text",
"analyzer": "standard"
},
"user_Gender": {
"type": "text"
},
"user_Name": {
"type": "text",
"analyzer": "standard"
},
"user_Photo": {
"type": "text"
},
"user_UserID": {
"type": "keyword"
}
}
}
}
}
}
My Query is this:
{
"index": "liveindex",
"type": "users",
"body": {
"from": 0,
"size": 50,
"query": {
"query_string": {
"fields": [
"user_Name"
],
"default_operator": "AND",
"query": "neel"
}
},
"sort": {
"_score": {
"order": "desc"
}
}
}
}
I am getting following results when I run above query:
Neel Chaudhary
ITZ NEEL
neel modi
Neel Yagnik
anu neel
swapna neel
I want the query to return those names first which have "Neel", or "neel" as first word. But as you can see the ITZ NEEL, anu neel is out of the desired order. I have applied sorting by user_Name also but there was no success. I know that Elastic search uses lexicographical order as opposed to alphabetical order.
Can anyone please help me in this?
回答1:
This is not an issue of lexicographical vs alphabetical order. You should create a keyword sub-field for your user_Name field so that you can later boost the documents with the neel prefix:
PUT liveindex
{
"settings": { <-- add these settings
"analysis": {
"normalizer": {
"lowercase": {
"type": "custom",
"filter": ["lowercase"]
}
}
}
},
"mappings": {
"users": {
"properties": {
"user_Confirmed": {
"type": "boolean"
},
"user_DateOfBirth": {
"type": "text"
},
"user_Email": {
"type": "text",
"analyzer": "standard"
},
"user_Gender": {
"type": "text"
},
"user_Name": {
"type": "text",
"analyzer": "standard",
"fields": { <-- add this sub-field
"sort": {
"type": "keyword",
"normalizer": "lowercase"
}
}
},
"user_Photo": {
"type": "text"
},
"user_UserID": {
"type": "keyword"
}
}
}
}
}
Then, index you data and finally use the following query, which will give a slight boost to documents having a user_Name field that starts with neel:
POST liveindex/_search
{
"from": 0,
"size": 50,
"query": {
"bool": {
"must": {
"query_string": {
"fields": [
"user_Name"
],
"default_operator": "AND",
"query": "neel"
}
},
"should": {
"prefix": {
"user_Name.sort": "neel"
}
}
}
},
"sort": {
"_score": {
"order": "desc"
}
}
}
You'll get the documents in the following order:
- Neel Yagnik
- neel modi
- Neel Chaudhary
- ITZ NEEL
- anu neel
- swapna neel
来源:https://stackoverflow.com/questions/52588144/how-to-do-alphabetical-sorting-on-analyzed-field-in-elastic-search-5-6