Elasticsearch的安装与入门
一、名词解释:
节点(Node):节点是一个ES的实例,一般一台主机上部署一个节点-
集群(Cluster):集群由若干节点组成,和任意节点的通信等价于和集群的通信
分片(Shard):一个索引会分成多个分片存储,分片数量在索引建立后不可更改
副本(Replica):副本是分片的一个拷贝,目的在于提高系统的容错性和搜索的效率
索引(Index):类似数据库的库
类型(Type):类似数据库的表
文档(Document):类似数据库的行,包含一个或多个Field
字段(Field):搜索的最小单元,可通过Mapping定义不同的属性(比如可否被搜索)
Transport:支持的交互协议
discovery.zen:自动发现集群节点的p2p系统
river:数据库
gateway:存储方式
二、安装:
1.首先安装JDK,设置好JAVA_HOME环境变量(export JAVA_HOME=.../java8),
查看Java环境
java -version
2.然后下载Elasticsearch。
下载地址:https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.0.1.zip
安装方法一:
解压并运行bin\elasticsearch.bat 开始安装
通过浏览器打开http://localhost:9200/查看安装是否成功
安装方法二:
解压,cmd进入bin目录:
service install
service start
通过浏览器打开http://localhost:9200/查看安装是否成功
关闭elasticsearch:
service stop
3.安装head插件
head插件用于在网页上管理、监视集群的状态。
拉取 https://github.com/mobz/elasticsearch-head 代码,将其放到./plugins/head 目录下。
cmd进入\bin目录,
然后执行:
plugin install mobz/elasticsearch-head
浏览器打开 http://localhost:9200/_plugin/head/ 查看
三、配置:
1)一台机器一个节点
打开/home/zkpk/elasticsearch-node1/config目录下的elasticsearch.yml 文件
配置文件中的一些配置点:
#设置集群名字
cluster.name: cswuyg_qa_pair_test
#设置node名字
node.name: xxx-node
#指定集群中的节点中有几个有master资格的节点。对于大集群可以写3个以上。
covery.zen.minimum_master_nodes: 2
#设置节点域名
network.host: 192.168.137.100
#设置是否打开多播发现节点,默认是true。
discovery.zen.ping.multicast.enabled: false
#发现其它节点时ping连接超时时间
discovery.zen.ping.timeout: 40s
#设置绑定的ip地址
network.bind_host: 192.168.137.100
#设置其它节点和该节点交互的ip地址。
network.publish_host: 192.168.137.100
#同时设置bind_host和publish_host上面两个参数。
network.host: 192.168.137.100
#设置内部传输端口和外部HTTP访问端口
transport.tcp.port: 9302
http.port: 8302
#discovery.zen.ping.unicast.hosts:["节点1的 ip","节点2 的ip","节点3的ip"]
#指明集群中其它可能为master的节点ip,以防es启动后发现不了集群中的其他节点。
discovery.zen.ping.unicast.hosts: ["192.168.137.100", "192.168.137.101","192.168.137.100:9301"]
#设置中文切词插件
index.analysis.analyzer.ik.type: "ik"
2)一台机器多个节点
拷贝 elasticsearch-node1 整个文件夹,命名为elasticsearch-node2
对于单机多节点的es集群,一定要注意修改 transport.tcp.port 和http.port 的默认值保证节点间不冲突。
修改elasticsearch.yml中的节点名称和端口号:
node.name: "es-node3"
transport.tcp.port: 9301
http.port: 9201
启动:
启动之前设置ES使用的内存:export ES_HEAP_SIZE=10g。
elasticsearch -d 以守护进程方式启动,启动之后,就可以在浏览器里使用head插件看到集群信息,如:
http://host_name_xxx:port_yyy/_plugin/head/
四、使用:
1.创建一个index:
POST http://192.168.137.100:9200/test_index
查看创建的index:
GET http://192.168.137.100:9200/_cat/indices?v
删除一个索引
DELETE http://192.168.137.100:9200/customer?pretty
2.写入数据:
POST http://xxxhost:8201/qa_xx2/qa_xx3/1234
{
"title":"cswuyg test",
"content":"this is test by cswuyg。。。"
}
{
"_index":"qa_xx2",
"_type":"qa_xx3",
"_id":"1234",
"_version":1,
"_shards":{
"total":2,
"successful":2,
"failed":0
},
"created":true
}
3.查询数据:
(1)使用id直接查:
GET http://xxxhost:8201/qa_xx2/qa_xx3/1235
(2)DSL查询:
往查询url POST数据即可:
URL格式:http://xxxhost:8201/qa_xx2/qa_xx3/_search
a. 查询title中包含有cswuyg字段的文档。Highlight设置高亮命中的词。POST方法的body:
{
"query": {
"match": {
"title": {
"query": "cswuyg "
}
}
},
"highlight": {
"fields": {
"title": {
}
}
}
}
b. bool组合查询,命中的文档的title字段必须能命中“餐厅”、“好吃”、“深圳”,可以是完全命中,也可以是名字其中的个别字。“便宜”则是可选命中。
POST方法的body:
如果要求每一个字都命中,可以把match修改为match_phrase。
例子:要求必须完全命中“酒后”和“标准",“驾驶”可以部分命中
c. 给查询词设置权重(boost)。POST方法的body:
d. filter查询,也就是kv查询,不涉及检索的相关性打分,title必须是完全命中,如果建库时是有对这个字段切词的,则查询时,需要是切词后的某个词去查询,如“今天天气”,建库切词为“今天”和“天气”,那么filter查询的时候需要使用“今天”或者“天气”才能命中。POST方法的body:
e. 完全匹配某个短语,这就要求“好厉害”三个字组成的词必须在文档中出现,不能是只出现其中的个别字(match就是这样)。POST方法的body:
(3)运维
a. 去掉副本,调研的时候希望不要副本,这样子写入会快点
PUT http://192.168.137.100:8202/qa_pair2/_settings
{
"number_of_replicas" : 0
}
4.切词:使用ik中文切词插件
Elasticsearch默认的中文切词插件是单字切词,这不能满足我们要求,需要安装中文切词插件。
插件github地址:https://github.com/medcl/elasticsearch-analysis-ik
源码安装:编译时需要联网,可以在windows下编译完之后,把elasticsearch-analysis-ik-1.9.3.zip拷贝到linux机器的./plugin/head目录下解压。
配置:在配置文件./config/elasticsearch.yml末尾添加配置: index.analysis.analyzer.ik.type: "ik"
测试ik切词:http://host_name_xx:port_yyy/qa_pair/_analyze?analyzer=ik&pretty=true&text=我是中国人"
5.使用python读写Elasticsearch
使用pip安装elasticsearch
1)读取文件批量插入数据示例:
#!/home/work/bin/python
#-*-coding:utf8-*-
"""
读取文件,入库到es
使用:python insert_demo.py xxx_file_name
Authors: cswuyg
Date: 2016.06.18
"""
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
from elasticsearch import exceptions
import traceback
import datetime
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
#设置mappings
def _create_index(es, index_name="cswuyg", doc_type_name="cswuyg"):
my_settingss = {
'number_of_shards': 18,
'number_of_replicas': 0
}
my_mappings = {
"cswuyg": {
'_all': {
'enabled': 'false'
},
"properties": {
"title": {
'type': 'string',
'store': 'no',
'term_vector': 'with_positions_offsets',
'analyzer': 'ik_max_word',
'boost': 8
},
"url": {
"type": "string",
'index': 'not_analyzed'
},
'content': {
'type': 'string',
'store': 'no',
'term_vector': 'with_positions_offsets',
'analyzer': 'ik_max_word',
'boost': 8
}
}
}
}
settings = {
'settings': my_settingss,
'mappings': my_mappings
}
create_index = es.indices.create(index=index_name, body=settings)
#将文件中的数据存储到es中
def _save_data(es, input_file):
#读入数据
all_data = list()
count = 0
with open(input_file) as f_r:
for line in f_r:
count += 1
all_data.append({
'_index': 'cswuyg',
'_type': 'cswuyg',
'_source': {
'title': line
}
})
if len(all_data) == 100:
success, _ = bulk(es, all_data, index='cswuyg', raise_on_error=True)
all_data = list()
print('{1}: finish {0}'.format(count, input_file))
if len(all_data) != 0:
success, _ = bulk(es, all_data, index='cswuyg', raise_on_error=True)
all_data = list()
print('{1}: finish {0}'.format(count, input_file))
print('{0}: finish all'.format(input_file))
def _insert_data(es, file_name):
start_time = datetime.datetime.now()
_save_data(es, file_name)
cost_time = datetime.datetime.now() - start_time
print('all cost time{0}'.format(cost_time))
def _main():
if len(sys.argv) != 2:
print('need file argument')
return
es = Elasticsearch(hosts=["10.200.100.80:8301"], timeout=500)
try:
_create_index(es)
except exceptions.RequestError:
print(traceback.format_exc())
_insert_data(es, sys.argv[1]);
if __name__ == '__main__':
_main()
测试文件数据格式:
我是中国人
我爱中国
2)检索示例(从文件中获取检索条件:切好词且打好分的Term):
#!/home/work/bin/python
#-*-coding:utf8-*-
"""
检索 es
策略:
从文件中读取已经切好词,且给好权重的term,且选好必选term的一行文本,处理成match_phrase + bool查询
默认策略2
使用方法:python search_demo.py test_file
output:
es_query
query\ttitle\tsall_score
output demo:
{'query': {'bool': {'should': [{'match': {'title': {'query': '\xe6\x88\x91', 'boost': 0.2}}}], 'must': [{'match_phrase': {'title': {'query': '\xe4\xb8\xad\xe5\x9b\xbd', 'boost': 0.69}}}, {'match_phrase': {'title': {'query': '\xe7\x88\xb1', 'boost': 0.11}}}]}}}
我爱中国 我爱中国 {"should": ["我"], "score": {"我": 0.2, "中国": 0.69, "爱": 0.11}, "must": ["中国", "爱"]}
我爱中国 我爱中国 {"should": ["我"], "score": {"我": 0.2, "中国": 0.69, "爱": 0.11}, "must": ["中国", "爱"]}
Authors: cswuyg
Date: 2016.06.18
"""
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
from elasticsearch import exceptions
import sys
import json
from log import logger
import traceback
reload(sys)
sys.setdefaultencoding('utf-8')
def _release_es_query_by_file_info(file_info):
#输入格式: raw_query\tmust_term\tshould_term\tall_score
logger.debug('file_info:{0}'.format(file_info))
file_info_list = file_info.split('\t')
print file_info_list
raw_query = file_info_list[0]
must_term = file_info_list[3]
should_term= file_info_list[4]
all_score = file_info_list[5]
json_score = json.loads(all_score, encoding='utf-8')
ret_obj = {}
ret_obj['must'] = must_term.split()
ret_obj['should'] = should_term.split()
ret_obj['score'] = json_score
bool_query = dict()
must_query = list()
should_query = list()
for item in must_term.split(' '):
must_query.append({'match_phrase': {'title': {'query': item, 'boost': json_score[unicode(item)]}}})
bool_query['must'] = must_query
for item in should_term.split(' '):
should_query.append({'match': {'title': {'query': item, 'boost': json_score[unicode(item)]}}})
bool_query['should'] = should_query
es_query = {'query': {'bool': bool_query}}
print es_query
return raw_query, es_query, json.dumps(ret_obj, ensure_ascii=False)
def _do_query_use_file_info(es, file_info):
raw_query, query, all_score = _release_es_query_by_file_info(file_info.strip('\r\n'))
res = es.search(index='cswuyg', doc_type='cswuyg', body=query, size=100)
if (len(res['hits']['hits']) == 0):
logger.debug('len(res["hits"]["hits"]) == 0')
print("{0}\t{1}\t{2}".format(raw_query, "", all_score))
return
for item in res['hits']['hits']:
try:
print("{0}\t{1}\t{2}".format(raw_query, item['_source']['title'].strip('\r\n'), all_score))
except:
logger.debug(traceback.format_exc())
logger.debug(item['_source']['title'])
print('\r\n')
def _main():
if len(sys.argv) != 2:
print('argv error')
return
else:
print('argv[1] = {0}'.format(sys.argv[1]))
es = Elasticsearch(hosts=["10.200.100.80:8301"], timeout=5000)
with open(sys.argv[1]) as f_r:
for item in f_r:
try:
_do_query_use_file_info(es, item)
except:
logger.debug(traceback.format_exc())
if __name__ == '__main__':
_main()
测试文件数据格式:
我爱中国 中国 爱 我 {"我": 0.20, "中国": 0.69, "爱": 0.11}
参考:
安装配置
http://blog.csdn.net/sinat_28224453/article/details/51134978
http://www.cnblogs.com/cswuyg/p/5651620.html
http://blog.csdn.net/ebw123/article/details/46707559
用户权限管理
http://blog.csdn.net/napoay/article/details/52201558
http://rockelixir.iteye.com/blog/1890879
Elasticsearch的安装与入门
最新推荐文章于 2022-10-29 21:45:47 发布