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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM