python | Elasticsearch-dsl常用方法总结(join为案例)

    Elasticsearch DSL是一个高级库,其目的是帮助编写和运行针对Elasticsearch的查询。它建立在官方低级客户端(elasticsearch-py)之上。

    它提供了一种更方便和习惯的方式来编写和操作查询。它接近Elasticsearch JSON DSL,反映了它的术语和结构。它直接使用定义的类或类似查询集的表达式来暴露从Python的DSL的整个范围。

1.导入包

# 导入包
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search, Q

2.连接es 并创建dsl 查询

es = Elasticsearch(hosts="http://xxxxx:9222/")  # 连接es

s = Search(using=es, index="xxxxx")   #using: 指定es 引擎  index:指定索引

3.增删改查的基本使用

3.1 创建索引

  首先定义映射关系(也可以不指定,如果想要使用join功能必须手动定义)

# 創建映射
mappings = {
    "mappings": {
        "data": {        # "文档类型"
            "properties": { 
                "xxx": {     # "索引名"
                    "type": "join",   # "如果想用join功能必须定义类型为join"
                    "relations": {
                        "parent": "child"    # 父类对应子类  attr 是父文档 info子文档(自己指定)
                    }
                }
            }
        }
    }
}

创建

# 创建index 库
if es.indices.exists("xxx") is not True:   
    es.indices.create(index="xxx", body=mappings)

删除

es.delete(index='xxx', doc_type='xxx', id='xxx')

更新

es.update(index='xxx', doc_type='xxx', id='xxx', body={待更新字段})

查询

  查询所有

response = s.params(size=1000).filter("match_all").sort("_id").execute()  # 查询1000条数据 并根据_id进行排序

#注意: 如果不指定条数 默认只查询10条数据

  根据父级查询子级

response = s.query("has_parent", parent_type="xxx", query={"match": {"id": "1"}}).execute()

  根据子级查询父级

response = s.query("has_child", type="xxx", query={"match": {"id": "5"}}).execute()

  将查询结果转化为字典

response.to_dict()
原文地址:https://www.cnblogs.com/damon-/p/9647081.html