[英]Elasticsearch - match_phrase query sort by int
我有“設備”類型的文檔,我使用以下查詢(使用Flask和Elasticsearch作為api)按型號進行搜索:
match handset
query = {
"query": {
"match_phrase": {
"model": model_name
}
},
"track_scores": True,
"size": 1,
"sort":
[
{"_score": {"order": "desc"}},
{"model": {"order": "asc"}}
]
}
device = es.search(body=query, doc_type='device')
這將返回“型號”最接近請求(型號名稱)的單個設備。
設備清單示例:
[{ "id":482,
"memory":"16",
"model":"iPhone 5s 16GB" },
{ "id":483,
"memory":"32",
"model":"iPhone 5s 32GB" },
{ "id":484,
"memory":"16",
"model":"iPhone 5c 16GB" },
{ "id":486,
"memory":"64",
"model":"iPhone 6 64GB" },
{ "id":485,
"memory":"32",
"model":"iPhone 6 32GB" }]
如何更改它,使其返回具有最低內存的設備?
>>> query.query.match_phrase.model = 'iPhone 5s'
>>> device = es.search(body=query, doc_type='device')
{ "id":482,
"memory":"16",
"model":"iPhone 5s 16GB" }
>>> query.query.match_phrase.model = 'iPhone 6'
>>> device = es.search(body=query, doc_type='device')
{ "id":485,
"memory":"32",
"model":"iPhone 6 32GB" }
任何線索高度贊賞。
我會在映射中將"memory"
字段的類型更改為"integer"
,並適當地對數據建立索引,這樣很容易獲得所需的結果。
因此,使用這樣的映射:
PUT /test_index
{
"mappings": {
"doc": {
"_id": {
"path": "id"
},
"properties": {
"id": {
"type": "integer"
},
"memory": {
"type": "integer"
},
"model": {
"type": "string"
}
}
}
}
}
這些文件的索引為:
POST /test_index/doc/_bulk
{"index":{}}
{"id":482,"memory":16,"model":"iPhone 5s 16GB"}
{"index":{}}
{"id":483,"memory":32,"model":"iPhone 5s 32GB"}
{"index":{"_id":1}}
{"id":484,"memory":16,"model":"iPhone 5c 16GB"}
{"index":{}}
{"id":486,"memory":64,"model":"iPhone 6 64GB"}
{"index":{}}
{"id":485,"memory":32,"model":"iPhone 6 32GB"}
{"index":{}}
您可以這樣查詢,以在"iPhone 5s"
上獲得最低的內存"iPhone 5s"
:
POST /test_index/_search
{
"query": {
"match": {
"model": {
"query": "iPhone 5s",
"operator": "and"
}
}
},
"sort": [
{
"memory": {
"order": "asc"
}
}
],
"size": 1
}
...
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"hits": {
"total": 2,
"max_score": null,
"hits": [
{
"_index": "test_index",
"_type": "doc",
"_id": "482",
"_score": null,
"_source": {
"id": 482,
"memory": 16,
"model": "iPhone 5s 16GB"
},
"sort": [
16
]
}
]
}
}
這是我使用的代碼:
http://sense.qbox.io/gist/8441d7379485e03a75fdbaa9ae0bf9748098be33
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.