elasticsearch dsl使用

elasticsearch_dsl 库可以方便的生成一些复杂的 dsl 语句,而不用自己去写 json.

指定 _source

指定确定的字段

1
2
3
4
5
6
7
from elasticsearch_dsl import Search

s = Source()
s = s.source(['attacker_ip', 'attacker_id'])
print(s.to_dict())

# {'query': {'match_all': {}}, '_source': ['attacker_ip', 'attacker_id']

使用 includeexclude ,需要注意的是两种方式不能同时使用

1
2
3
4
5
6
7
8
9
from elasticsearch_dsl import Search

s = Source()

# 需要注意的是 source 并不是在原有对象上修改,需要重新赋值
s = s.source(include=['attacker_id'], exclude=["time*"])
print(s.to_dict())

# {'query': {'match_all': {}}, '_source': {'include': ['attacker_id'], 'exclude': ['time*']}}

逻辑操作

1
Q() & Q() | ~Q()

取子属性

1
2
# eg 要获取 attacker.city, 使用 __ 代替 .
Q("term", attacker__city="杭州")

嵌套

1
city_q = Q('nested', path='victims', query=~Q('term', victims__location__city=""))

对应下面的 json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
"query": {
"bool": {
"must": [
{
"nested": {
"path": "victims",
"query": {
"bool": {
"must_not": [
{
"term": {
"victims.location.city": ""
}
}
]
}
}
}
}
]
}
}
}