目录
聚合嵌套(嵌套时支持bucket、metric、pipeline)
在使用Python客户端操作ES时,需要编写ES DSL语句对ES进行查询操作。但体验下来,发现以下缺点:
字段冗长,容易出现语法错误,如不正确的嵌套,难以修改(如添加另一个过滤器)
基于此目的,发现了解到了elasticsearch-dsl库。
将传统的JSON DSL语句,映射为Python类、对象操作,使其两者相互转换互通,减少手动编写JSON DSL语句的繁琐,提高可维护性。
一、创建连接(可选)
dsl库支持查询,并序列化结果。
若仅为了生成DSL语句,则无需创建连接。
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search
es = Elasticsearch(hosts="127.0.0.1:9200")
s = Search(using=es, index="teset_index")
二、基本查询(Q方法)
2.1 query
空查询
# 空查询
s = Search().query(Q())
{
"query": {
"match_all": {}
}
}
基于字典生成Search对象
# 基于字典生成Search对象
s = Search.from_dict({"track_total_hits": True}).query(Q())
{
"query": {
"match_all": {}
},
"track_total_hits": true
}
Query查询语句
# query查询
s = Search.from_dict({"track_total_hits": True}).query(Q())
s = s.query("multi_match", query='python django', fields=['title', 'body'])
{
"query": {
"multi_match": {
"query": "python django",
"fields": [
"title",
"body"
]
}
},
"track_total_hits": true
}
组合查询
should
# should
s = Search().query(Q("match", title='python') | Q("match", title='django'))
{
"query": {
"bool": {
"should": [
{
"match": {
"title": "python"
}
},
{
"match": {
"title": "django"
}
}
]
}
}
}
must
# must
s = Search().query(Q("match", title='python') & Q("match", title='django'))
{
"query": {
"bool": {
"must": [
{
"match": {
"title": "python"
}
},
{
"match": {
"title": "django"
}
}
]
}
}
}
must_not
# must_not
s = Search().query(~Q("match", title='python'))
{
"query": {
"bool": {
"must_not": [
{
"match": {
"title": "python"
}
}
]
}
}
}
2.2 filter
空查询
# 空查询
s = Search().filter(Q())
{
"query": {
"bool": {
"filter": [
{
"match_all": {}
}
]
}
}
}
terms
# trems
s = Search().filter('terms', tags=['search', 'python'])
{
"query": {
"bool": {
"filter": [
{
"terms": {
"tags": [
"search",