更像是这个弹性搜索:同样请求不同的响应

时间:2016-05-23 08:29:42

标签: python curl elasticsearch request

我正在玩弹性搜索,我遇到了一个奇怪的问题:我有更多像这样的请求,我以多种方式建立:

curl -XGET 'http://127.0.0.1:9200/train-recipe/_search' -d '{
    'query': {
        'more_like_this': {
            'fields': ['ingredients'],
            'max_query_terms': 12,
            'like': [{'_type': 'recipe', '_id': 2938, '_index': 'train-recipe'}],
            'min_term_freq': 1
        }
    }, 
    'from': 0, 
    'size': 10
}'

我收到以下回复:

{"error":{"root_cause":[{"type":"json_parse_exception","reason":"json_parse_exception: Unrecognized token 'ingredients': was expecting ('true', 'false' or 'null')\n at [Source: [B@6f7a6ea4; line: 4, column: 34]"}],"type":"search_phase_execution_exception","reason":"all shards failed","phase":"query","grouped":true,"failed_shards":[{"shard":0,"index":"train-recipe","node":"kfORe_NWSE2gIeHSHGgIQw","reason":{"type":"query_parsing_exception","reason":"Failed to parse","index":"train-recipe","caused_by":{"type":"json_parse_exception","reason":"json_parse_exception: Unrecognized token 'ingredients': was expecting ('true', 'false' or 'null')\n at [Source: [B@6f7a6ea4; line: 4, column: 34]"}}}]},"status":400}

我也有这个请求,对我而言与第一个请求相同:

curl -XGET 'http://127.0.0.1:9200/train-recipe/_search' -d '{
  "query": {
    "more_like_this": {
      "fields": ["ingredients"],
      "like": [{"_index" : "train-recipe","_type" : "recipe","_id" : 2938}],
      "min_term_freq": 1,
      "max_query_terms": 12
    }
  },
    'from' : 0,
    'size':10
}'

但是这个完美无缺。我也尝试使用python请求,如下所示:

def build_mlt(nb, doc_id):
   mlt = {}
   mlt['from'] = 0
   mlt['size'] = nb
   mlt['query'] = {}
   mlt['query']['more_like_this'] = {}
   mlt['query']['more_like_this']['fields'] = ['ingredients']
   mlt['query']['more_like_this']['like'] = [{"_index" : "train-recipe","_type" : "recipe","_id" : doc_id}]
   mlt['query']['more_like_this']['min_term_freq'] = 1
   mlt['query']['more_like_this']['max_query_terms'] = 10
   return mlt

def get_similar(nb, doc_id):
   mlt = build_mlt(10, 2938)
   response = requests.get("http://localhost:9200/test-recipe/recipe/_search", data=json.dumps(mlt))
   print json.loads(response.text)

这次我有另一个回应:

{u'hits': {u'hits': [], u'total': 0, u'max_score': None}, u'_shards': {u'successful': 5, u'failed': 0, u'total': 5}, u'took': 2, u'timed_out': False}

对我来说,三个要求是相同的。我根据我的函数melt_builder生成的字典做了第二个。有人可以向我解释为什么我会得到三种不同的回答吗?

2 个答案:

答案 0 :(得分:2)

在第一种情况下,单引号必定存在问题。您在JSON中有单引号,并且在JSON周围也有单引号,以便将有效负载传递给-d参数。

在第二种情况下,你使用双引号,所以你很好。

在第三种情况下,您应该使用requests.post()发送请求,否则不会发送带有查询的有效负载。

答案 1 :(得分:2)

如上所述:python: single vs double quotes in JSON 你需要在json中使用双打引号。

第三个案例由Val解释。