在 Elasticsearch 中,我存储数据如下:
{
"name" : "John Doe",
"country" : "India"
},
{
"name" : "John Doe",
"country" : "USA"
}
如果用户输入“John”,我将通过以下查询按名称字段进行搜索:
{
"from": 0,
"size": 10,
"query": {
"bool": {
"must": [
{
"query_string": {
"query": "name:(John*)"
}
}
]
}
}
}
并得到类似于上面查询的结果:
{
"name" : "John Doe",
"country" : "India"
},
{
"name" : "John William",
"country" : "USA"
},
{
"name" : "John Smith",
"country" : "Canada"
},
{
"name" : "John Lobo",
"country" : "India"
}
我得到的所有结果都带有约翰的名字,但我希望约翰来自国家:印度位居榜首,其次是加拿大,然后是所有其他国家。这意味着我必须分别对国家=印度的数据给予比国家=加拿大更多的权重。
国家=印度和加拿大的数据在搜索结果中应该有更高的分数。
我在elasticsearch中发现了一些按值提升功能,但无法根据需要进行查询。我只能在此处指定一个字段值。
{
"query": {
"boosting": {
"positive": {
"term": {
"country.keyword": "India"
}
},
"negative": {
"match_all": {}
},
"negative_boost": 0.5
}
}
}
为了您更新的文件
PUT /sorting_by_country/_bulk?refresh
{"create":{"_id":1}}
{"name":"John Doe","country":"India"}
{"create":{"_id":2}}
{"name":"John William","country":"USA"}
{"create":{"_id":3}}
{"name":"John Smith","country":"Canada"}
{"create":{"_id":4}}
{"name":"John Lobo","country":"India"}
{"create":{"_id":5}}
{"name":"James McHartley","country":"Ireland"}
尝试以下查询。
should
部分包含国家及其增强功能
GET /sorting_by_country/_search?filter_path=hits.hits
{
"from": 0,
"size": 10,
"query": {
"bool": {
"must": [
{
"query_string": {
"query": "name:(John*)"
}
}
],
"should": [
{
"term": {
"country.keyword": {
"value": "India",
"boost": 20
}
}
},
{
"term": {
"country.keyword": {
"value": "Canada",
"boost": 2
}
}
}
]
}
}
}
回应
{
"hits" : {
"hits" : [
{
"_index" : "sorting_by_country",
"_type" : "_doc",
"_id" : "1",
"_score" : 18.509373,
"_source" : {
"name" : "John Doe",
"country" : "India"
}
},
{
"_index" : "sorting_by_country",
"_type" : "_doc",
"_id" : "4",
"_score" : 18.509373,
"_source" : {
"name" : "John Lobo",
"country" : "India"
}
},
{
"_index" : "sorting_by_country",
"_type" : "_doc",
"_id" : "3",
"_score" : 3.7725885,
"_source" : {
"name" : "John Smith",
"country" : "Canada"
}
},
{
"_index" : "sorting_by_country",
"_type" : "_doc",
"_id" : "2",
"_score" : 1.0,
"_source" : {
"name" : "John William",
"country" : "USA"
}
}
]
}
}
根据https://www.elastic.co/guide/en/elasticsearch/reference/7.17/sort-search-results.html
您可以应用基于脚本的排序,给出的示例是
{
"query": {
"term": { "user": "kimchy" }
},
"sort": {
"_script": {
"type": "number",
"script": {
"lang": "painless",
"source": "doc['field_name'].value * params.factor",
"params": {
"factor": 1.1
}
},
"order": "asc"
}
}
}
因此,您可以传递您喜欢的脚本,从逻辑上讲,它可以对类似的值进行升序排序
AAAAA
AAAAB