Python中使用ElasticSearch的指南
文章目录
依赖下载
pip install elasticsearch
# 豆瓣源
pip install -i https://pypi.doubanio.com/simple/ elasticsearch
连接elasticsearch
连接 elasticsearch 有以下几种连接方式:
from elasticsearch import Elasticsearch
# es = Elasticsearch() # 默认连接本地 elasticsearch
# es = Elasticsearch(['127.0.0.1:9200']) # 连接本地 9200 端口
es = Elasticsearch(
["192.168.1.10", "192.168.1.11", "192.168.1.12"], # 连接集群,以列表的形式存放各节点的IP地址
sniff_on_start=True, # 连接前测试
sniff_on_connection_fail=True, # 节点无响应时刷新节点
sniff_timeout=60 # 设置超时时间
)
配置忽略响应状态码
es = Elasticsearch(['127.0.0.1:9200'],ignore=400) # 忽略返回的 400 状态码
es = Elasticsearch(['127.0.0.1:9200'],ignore=[400, 405, 502]) # 以列表的形式忽略多个状态码
示例
from elasticsearch import Elasticsearch
es = Elasticsearch() # 默认连接本地 elasticsearch
print(es.index(index='py2', doc_type='doc', id=1, body={'name': "张开", "age": 18}))
print(es.get(index='py2', doc_type='doc', id=1))
第 1 个 print 为创建 py2
索引,并插入一条数据,第2个 print 查询指定文档。
查询结果如下:
{'_index': 'py2', '_type': 'doc', '_id': '1', '_version': 1, 'result': 'created', '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 0, '_primary_term': 1}
{'_index': 'py2', '_type': 'doc', '_id': '1', '_version': 1, 'found': True, '_source': {'name': '张开', 'age': 18}}
Elasticsearch for Python之操作
Python 中关于 elasticsearch 的操作,主要集中一下几个方面:
mappings
。结果过滤
print(es.search(index='py2', filter_path=['hits.total', 'hits.hits._source'])) # 可以省略 type 类型
print(es.search(index='w2', doc_type='doc')) # 可以指定 type 类型
print(es.search(index='w2', doc_type='doc', filter_path=['hits.total']))
filter_path
参数用于减少elasticsearch返回的响应,比如仅返回hits.total
和hits.hits._source
内容。
除此之外,filter_path
参数还支持*
通配符以匹配字段名称、任何字段或者字段部分:
print(es.search(index='py2', filter_path=['hits.*']))
print(es.search(index='py2', filter_path=['hits.hits._*']))
print(es.search(index='py2', filter_path=['hits.to*'])) # 仅返回响应数据的 total
print(es.search(index='w2', doc_type='doc', filter_path=['hits.hits._*'])) # 可以加上可选的 type 类型
ElasticSearch(es 对象)
# print(es.index(index='w2', doc_type='doc', id='4', body={"name":"可可", "age": 18})) # 正常
# print(es.index(index='w2', doc_type='doc', id=5, body={"name":"卡卡西", "age":22})) # 正常
# print(es.index(index='w2', id=6, body={"name": "鸣人", "age": 22})) # 会报错,TypeError: index() missing 1 required positional argument: 'doc_type'
print(es.index(index='w2', doc_type='doc', body={"name": "鸣人", "age": 22})) # 可以不指定id,默认生成一个id
print(es.get(index='w2', doc_type='doc', id=5)) # 正常
print(es.get(index='w2', doc_type='doc')) # TypeError: get() missing 1 required positional argument: 'id'
print(es.get(index='w2', id=5)) # TypeError: get() missing 1 required positional argument: 'doc_type'
index
要搜索的以逗号分隔的索引名称列表; 使用 _all 或空字符串对所有索引执行操作。doc_type
要搜索的以逗号分隔的文档类型列表; 留空以对所有类型执行操作。body
使用 Query DSL(QueryDomain Specific Language 查询表达式)的搜索定义。_source
返回_source
字段的 true 或 false,或返回的字段列表,返回指定字段。_source_exclude
要从返回的_source
字段中排除的字段列表,返回的所有字段中,排除哪些字段。_source_include
从_source
字段中提取和返回的字段列表,跟_source
差不多。print(es.search(index='py3', doc_type='doc', body={"query": {"match":{"age": 20}}})) # 一般查询
print(es.search(index='py3', doc_type='doc', body={"query": {"match":{"age": 19}}},_source=['name', 'age'])) # 结果字段过滤
print(es.search(index='py3', doc_type='doc', body={"query": {"match":{"age": 19}}},_source_exclude =[ 'age']))
print(es.search(index='py3', doc_type='doc', body={"query": {"match":{"age": 19}}},_source_include =[ 'age']))
print(es.get_source(index='py3', doc_type='doc', id='1')) # {'name': '王五', 'age': 19}
body = {
"query": {
"match": {
"age": 18
}
}
}
print(es.count(index='py2', doc_type='doc', body=body)) # {'count': 1, '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0}}
print(es.count(index='py2', doc_type='doc', body=body)['count']) # 1
print(es.count(index='w2')) # {'count': 6, '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0}}
print(es.count(index='w2', doc_type='doc')) # {'count': 6, '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0}}
print(es.create(index='py3', doc_type='doc', id='1', body={"name": '王五', "age": 20}))
print(es.get(index='py3', doc_type='doc', id='3'))
在内部,调用了 index,等价于:
print(es.index(index='py3', doc_type='doc', id='4', body={"name": "麻子", "age": 21}))
但个人觉得没有 index 好用!
4
的文档,但不能删除索引,如果想要删除索引,还需要 es.indices.delete 来处理print(es.delete(index='py3', doc_type='doc', id='4'))
index
要搜索的以逗号分隔的索引名称列表; 使用 _all 或空字符串对所有索引执行操作。doc_type
要搜索的以逗号分隔的文档类型列表; 留空以对所有类型执行操作。body
使用 Query DSL 的搜索定义。print(es.delete_by_query(index='py3', doc_type='doc', body={"query": {"match":{"age": 20}}}))
print(es.exists(index='py3', doc_type='doc', id='1'))
print(es.info())
print(es.ping())
Indices(es.indices)
title
字段指定ik_max_word
查询粒度的mappings
。并应用到py4
索引中。这也是常用的创建自定义索引的方式。body = {
"mappings": {
"doc": {
"dynamic": "strict",
"properties": {
"title": {
"type": "text",
"analyzer": "ik_max_word"
},
"url": {
"type": "text"
},
"action_type": {
"type": "text"
},
"content": {
"type": "text"
}
}
}
}
}
es.indices.create('py4', body=body)
es.indices.analyze(body={'analyzer': "ik_max_word", "text": "皮特和茱丽当选“年度模范情侣”Brad Pitt and Angelina Jolie"})
print(es.indices.delete(index='py4'))
print(es.indices.delete(index='w3')) # {'acknowledged': True}
index
别名应指向的逗号分隔的索引名称列表(支持通配符),使用 _all对所有索引执行操作。name
要创建或更新的别名的名称。body
别名的设置,例如路由或过滤器。print(es.indices.put_alias(index='py4', name='py4_alias')) # 为单个索引创建别名
print(es.indices.put_alias(index=['py3', 'py2'], name='py23_alias')) # 为多个索引创建同一个别名,联查用
print(es.indices.delete_alias(index='alias1'))
print(es.indices.delete_alias(index=['alias1, alias2']))
print(es.indices.get_mapping(index='py4'))
print(es.indices.get_settings(index='py4'))
print(es.indices.get(index='py2')) # 查询指定索引是否存在
print(es.indices.get(index=['py2', 'py3']))
print(es.indices.get_alias(index='py2'))
print(es.indices.get_alias(index=['py2', 'py3']))
print(es.indices.get_field_mapping(fields='url', index='py4', doc_type='doc'))
print(es.indices.get_field_mapping(fields=['url', 'title'], index='py4', doc_type='doc'))
Cluster(集群相关)
print(es.cluster.get_settings())
print(es.cluster.health())
print(es.cluster.state())
print(es.cluster.stats())
Node(节点相关)
print(es.nodes.info()) # 返回所节点
print(es.nodes.info(node_id='node1')) # 指定一个节点
print(es.nodes.info(node_id=['node1', 'node2'])) # 指定多个节点列表
print(es.nodes.stats())
print(es.nodes.stats(node_id='node1'))
print(es.nodes.stats(node_id=['node1', 'node2']))
print(es.nodes.hot_threads(node_id='node1'))
print(es.nodes.hot_threads(node_id=['node1', 'node2']))
print(es.nodes.usage())
print(es.nodes.usage(node_id='node1'))
print(es.nodes.usage(node_id=['node1', 'node2']))
Cat(一种查询方式)
name
要返回的以逗号分隔的别名列表。format
Accept 标头的简短版本,例如 json,yamlprint(es.cat.aliases(name='py23_alias'))
print(es.cat.aliases(name='py23_alias', format='json'))
print(es.cat.allocation())
print(es.cat.allocation(node_id=['node1']))
print(es.cat.allocation(node_id=['node1', 'node2'], format='json'))
print(es.cat.count()) # 集群内的文档总数
print(es.cat.count(index='py3')) # 指定索引文档总数
print(es.cat.count(index=['py3', 'py2'], format='json')) # 返回两个索引文档和
es.cat.fielddata
则查询现在哪些数据在内存中,数据大小等信息。print(es.cat.fielddata())
print(es.cat.fielddata(format='json', bytes='b'))
bytes
显示字节值的单位,有效选项为:'b','k','kb','m','mb','g','gb','t','tb' ,'p','pb'
format
Accept 标头的简短版本,例如 json,yaml
health
里面过滤出简洁的集群健康信息。print(es.cat.health())
print(es.cat.health(format='json'))
es.cat
的帮助信息。print(es.cat.help())
print(es.cat.indices())
print(es.cat.indices(index='py3'))
print(es.cat.indices(index='py3', format='json'))
print(len(es.cat.indices(format='json'))) # 查询集群中有多少索引
print(es.cat.master())
print(es.cat.master(format='json'))
print(es.cat.nodeattrs())
print(es.cat.nodeattrs(format='json'))
print(es.cat.nodes())
print(es.cat.nodes(format='json'))
print(es.cat.plugins())
print(es.cat.plugins(format='json'))
print(es.cat.segments())
print(es.cat.segments(index='py3'))
print(es.cat.segments(index='py3', format='json'))
print(es.cat.shards())
print(es.cat.shards(index='py3'))
print(es.cat.shards(index='py3', format='json'))
print(es.cat.thread_pool())
Snapshot(快照相关)
repository
存储库名称。snapshot
快照名称。body
快照定义。Task(任务相关)
作者:TMesh