Elasticsearch - match_phrase查询按int

时间:2015-07-14 17:52:18

标签: python elasticsearch flask

我有'设备'键入文档,我使用以下查询按模型搜索(使用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')

使用' model'返回单个设备最接近请求的(model_name)。

设备列表示例:

[{ "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" }

任何线索都非常感谢。

1 个答案:

答案 0 :(得分:1)

我会在映射中将"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"上的最低内存:

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