一、配置
python == 3.6/3.8
# 更高版本的elasticsearch会出现doc_type被统一成_doc导致旧版语句报错的情况
pip install elasticsearch==7.8.0
二、连接es
from elasticsearch import Elasticsearch
es = Elasticsearch('ip:port')
三、查看集群/索引的信息
参考:https://www.cnblogs.com/expiator/p/14847705.html
# 查看集群状态:
http://ip:port/_cat/health?v
# 查看集群节点信息
http://ip:port_nodes/stats?pretty
# 浏览器查看索引
# ip:路由地址;port:运行端口(默认9200);index_name:要查看的索引名称
# 查看所有索引
http://ip:port/_cat/indices?v&pretty
# 查看单个索引
http://ip:port/index_name/_settings?pretty
# 查看单个索引的数据结构
http://ip:port/index_name/?pretty
# python查看elasticsearch是否存在
# es.indices.exists(index="index_name")
# 删除索引
# es.indices.delete(index='index_name', ignore=[400, 404])
三、创建索引与映射
# 索引参数设置
# 索引的静态参数一旦被设置,不能改变;动态参数可以改变
def create_index(es, index_name):
settings = {
'settings':
{
"number_of_shards": 5, # 设置主索引的主分片数,静态参数
"number_of_replicas": 0, # 设置主索引的副本数,动态参数
"max_result_window": 10000000, # 设置一次检索最大返回数量
"track_total_hits": True, # 使最大返回设置生效的参数
}
}
if es.indices.exists(index_name):
print(u"%s 已存在" % index_name)
else:
es.indices.create(index=index_name, body=settings)
print(index_name + "索引创建成功")
res = es.indices.create(index='index_name', ignore=400)
print(res)
# 创建映射(索引内每一个字段的设置)
"""
分词器主要有两种情况会被使用:
第一种是插入文档时,将text类型的字段做分词然后插入倒排索引,对应analyzer
第二种就是在查询时,先对要查询的text类型的输入做分词,再去倒排索引搜索,对应search_analyzer
如果想要让 索引 和 查询 时使用不同的分词器,ElasticSearch也是能支持的,只需要在字段上加上search_analyzer参数
在索引时,只会去看字段有没有定义analyzer,有定义的话就用定义的,没定义就用ES预设的
在查询时,会先去看字段有没有定义search_analyzer,如果没有定义,就去看有没有analyzer,再没有定义,才会去使用ES预设的
"""
mapping = {
'properties': {
# 简单设置
'title': {
'type': 'string',
'analyzer': 'jieba',
},
# 较复杂的设置
'content': {
'include_in_all': True, # 控制_all查询时是否需要查询该字段,默认True,若是false将不会被_all查询
'analyzer': 'jieba', # 查询和索引统一的分词器
# 'searchAnalyzer': 'jieba', # 单独设置查询分词器
'index': "analyzed", # 控制字段怎样建索引或查询。no不能被查询;not_analyzed只存储原始值,不分词;analyzed分词存储
'boost': 2, # 控制该字段的查询权重,大于1会增加相对权重
'term_vector': 'with_positions_offsets', # 存储完整的term vector信息,包括field terms、position、offset
'type': 'string', # 旧版支持。从ElasticSearch 5.x开始不再支持string,由text和keyword类型替代。
},
}
}
# 设置mapping信息:可以指定字段的类型、是否进行分词、默认值、是否被索引
# 分词器analyzer和搜索分词器search_analyzer。ik_max_word为默认的英文分词器,jieba等其他分词器需要额外安装。
result = es.indices.put_mapping(index='index_name', doc_type='doc', body=mapping)
print(result)
四、查询索引
1、match_all查询所有
body = {
"query": {
"match_all": {},
},
"size": 50, # size不设置会默认返回5条
}
result = es.search(index='index_name', doc_type='doc_type', body=body)
2、分词相关查询
关键词 |
keyword类型 |
text类型 |
是否支持分词 |
term |
完全匹配 |
查询条件中关键词不会被分词,它必须整个关键词和document中的某个分词匹配,才能搜索到,多个分词时必须连续,顺序不能颠倒。 |
是 |
match |
完全匹配 |
match分词结果和text的分词结果有相同的即可 |
否 |
match_phrase |
完全匹配 |
match_phrase的分词结果必须在text字段分词中都包含,而且顺序必须相同,而且必须都是连续的。 |
是 |
query_string |
完全匹配 |
query_string中和match_string基本一样,区别是它不考虑顺序 |
是 |
# term是代表完全匹配,即不进行分词器分析,文档中必须包含整个搜索的词汇
body = {
"query": {
"term": {
"content": "汽车保养"
"from": 1, # 从第几个开始返回
"size": 30, # 一次返回多少个
}
}
}
# match 分词,部分匹配查询,包含文本分词后的一个或多个词即符合条件
bod