【问题标题】:Querying ElasticSearch with Python Requests使用 Python 请求查询 ElasticSearch
【发布时间】:2017-10-18 14:55:07
【问题描述】:

,当我尝试使用 python 请求查询 ElasticSearch 时,我不太能够检索结果。这是我的代码:

json_data = updateJson(sys.argv[1])

headers={'Accept': 'application/json', 'Content-type': 'application/json'}

elastic_url ='https://localhost:9200/logstash-kafka-wga-blueid-\*/_search'

query = json.dumps(json_data)

response = requests.get(elastic_url, data = query, auth=('xxx','xxx'), verify=False, headers = headers)

print response.text

我总是得到以下输出:

{"took":1,"timed_out":false,"_shards":{"total":0,"successful":0,"failed":0},"hits":{"total":0,"max_score":0.0,"hits":[]}}

但如果我尝试使用以下 CURL 命令,我会得到正确的结果。在上面的代码 json_data 中,从 abc.json 文件中读取 json。上面的代码有什么不对吗?

curl -X GET -k -u xxx:xxx https://localhost:9200/logstash-kafka-wga-blueid-\*/_search -d @temporaryRundeckReport.json

这是我的 updateJson() 方法:

def updateJson(fileName):
with open(fileName, 'r') as file:
    json_data = file.read()
    json_data = json_data.replace('%X-FORWARDED-HOST%', sys.argv[2]);
    json_data = json_data.replace('%TIME%', sys.argv[3]);
    json_data = json_data.replace('%INTERVAL%', sys.argv[4]);

with open('temporaryRundeckReport.json', 'w+') as file:
    os.chmod('temporaryRundeckReport.json',0o777)
    file.write(json_data)
    return json_data

【问题讨论】:

  • 你在命令行传递的查询是什么?你有什么理由不使用elasticsearch-py
  • 我从它读取 json 的位置传递文件“abc.json”的名称。
  • abc.json 中有什么内容? updateJson() 是做什么的?
  • 我已在原帖中添加了该方法。
  • 我正在使用通过 requests 模块存储在temporaryRundeckReport.json 中的确切json_object。为什么要修改结果?

标签: python json elasticsearch python-requests


【解决方案1】:

我认为你不需要在python版本中转义星*(删除斜杠):

elastic_url = 'https://localhost:9200/logstash-kafka-wga-blueid-*/_search'

另外,我建议使用python client library 而不是requests

【讨论】:

  • 但我在 elasticsearch 中的索引包含“*”字符。我发现我可以这样定义它:'localhost:9200/logstash-kafka-wga-blueid-\*/_search'
  • @akashag26 我并不是要删除* - 我的意思是你不需要* 之前的斜线(使用...blueid-* 而不是..blueid-\*)。斜线用于在shell中转义星号,但将url放入python变量时不需要。
猜你喜欢
  • 2013-04-02
  • 1970-01-01
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多