首页 > 编程语言 > 详细

python-elasticsearch基本用法

时间:2020-12-11 16:51:32      阅读:18      评论:0      收藏:0      [点我收藏+]

python-elasticsearch基本用法

一、安装

pip install elasticsearch			
pip install elasticsearch[async]	#支持异步的es库

二、实例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",
                    "index":True
                },
                "text": {
                    "type": "text",
                    "index":False
                },
                "userId": {
                    "type": "long",
                    "index": True
                },
                "reprinted": {
                    "type": "keyword",
                    "index": True
                },
            }
        # }
    }
}
#创建 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(index = "test", 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":"小明"}}}


#排序
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")

python-elasticsearch基本用法

原文:https://www.cnblogs.com/mrzhao520/p/14120991.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!