簡體   English   中英

使用Should和List的Elasticsearch和Python Bool查詢

[英]Elasticsearch and Python Bool Query using Should and a List

我目前正在編寫一個腳本,該腳本使用python和elasticsearch模塊讀取IP地址列表,然后創建要使用的查詢。

下面是一些代碼,應解釋我要做什么:

from elasticsearch import Elasticsearch
es = Elasticsearch(["serveraddress"])


with open(ipfile.txt', 'r') as f:
    ipList = [line.strip('\n') for line in f]

query = {"query":{"bool":{"should":[{"term":{"source":ipList}},{"term":{"destination":ipList}}]}}}

results = es.search(index=index, body=query)

但是,執行此操作后,出現以下錯誤:

<type 'str'>: (<type 'exceptions.TypeError'>, TypeError('string indices must be integers',))

測試完查詢后,看來問題出在多個術語和字符串中使用列表。

有人對此有解決方法嗎? 同樣,該腳本假設讀取的文件充滿了可能非常長的IP地址。

提前致謝!

我想通了。 可能有一種更簡單的方法來執行此操作,但以下是對我有用的方法。

with open(ipfile, 'r') as f:
            ipList = [line.strip('\n') for line in f]
shouldQuery = []
[shouldQuery.append({'term':{'source':'{}'.format(ip)}}) for ip in ipList]
[shouldQuery.append({'term':{'destination':'{}'.format(ip)}}) for ip in ipList]
query = {'query':{'bool':{'should':[shouldQuery]}}}

希望這對遇到類似問題的人有所幫助。 如果有人有更簡單的方法,請告知社區:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM