python-elasticsearch基本用法


python-elasticsearch基本用法

一、安裝

pip install elasticsearch			
pip install elasticsearch[async]	#支持異步

二、實例化es對象,創建index

from elasticsearch import Elasticsearch
from elasticsearch import AsyncElasticsearch

es = Elasticsearch(host="localhost", port=9200)
#es = AsyncElasticsearch()

body = {
    "settings": {
		"number_of_shards": 3,
		"number_of_replicas": 2
	},
    "mappings":{
        # "_doc":{
            "properties":{
                "id":{
                    "type":"integer",
                },
                "text": {
                    "type": "text",
                    "analyzer": "ik_max_word",  #指定ik分詞器,適用中文分詞。
                    "index":False
                },
                "userId": {
                    "type": "long",
                },
                "reprinted": {
                    "type": "keyword",
                },
            }
        # }
    }
}
#創建 index
es.indices.create(index = "test", body = body)
#刪除 index
es.indices.delete(index = 'test')

三、增刪改查

#插入數據
es.index(index = "test", doc_type = "_doc", id = 1, body = {"id":1, "name":"小明"})
#可以不用指定id,create會自動添加id。
es.create(index="test", doc_type = "_doc",id = 2, body = {"id":2, "name":"小紅"})

#刪除指定數據
es.delete(index='test', doc_type='_doc', id=1)

#修改字段
es.update(index = "test", doc_type = "_doc", id = 1, body = {"doc":{"name":"張三"}})

#查詢數據
es.get(index = "test", doc_type = "_doc", id = 1)
es.search(index = "test", doc_type = "_doc", body = query)
#滾動分頁的func,第四塊部分 分頁查詢中 說明
es.scroll(scroll_id = "scroll_id", scroll = "5m")


#批量插入&批量更新
"""
{
	'_index':'test',
	'_type':'_doc',
	'_id':20,
	'doc':{'name':'李四', 'id':20},
}
	插入的每一個數據中,都需要指定 _index,_type,_id 更新、插入的數據放在doc中
"""
from elasticsearch.helpers import async_bulk,bulk
async def main():
    await async_bulk(es, data)
bulk(es, data)

四、es.search篩選數據的參數

es.search(index = "test", doc_type = "_doc", body = body, size = 10)
"""
index、doc_type、body
size = 10 : 返回的數據量
filter_path = [ 'hits.hits._id','hits.hits._type']: 用於指定響應的內容
default_operator: 指定查詢的運算符 AND或者OR 默認值為:OR
from_ = 0 : 返回數據的起始值,用於分頁
scroll = "5m" : 是否記錄滾動翻頁的索引值, 記錄5分鍾
"""


#返回所有數據
body = {"query":{"match_all": {}}}
#指定檢索字段
body = {"query":{"match": {"name":"小明"}}}
#范圍查詢
"""
gt:大於
gte:大於等於
lt:小於
lte:小於等於
"""
{"query":{"range":{"testTime":{"gte":"2020-12-01", "lte":"2020-12-31"}}}}



#排序
body = {
    "query":{...}, 
    "sort":[
        {
            "id(排序字段)":{
                "order" : "desc"   #asc\desc  升序\降序
            }
        }
    ]
}



#分頁,從第10個數據開始,返回10條數據。   ==   [10:20]
es.search(size = 10, from_ = 10)

#使用滾動分頁,速度快,查詢后會記錄最后一條數據,不適用跳頁查詢。
#響應返回 _scroll_id字段、調用es.scroll方法返回下一頁。
es.search(scroll = "5m")
es.scroll(scroll_id = "_scroll_id", scroll = "5m")


免責聲明!

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



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