最近,工作中有2个项目使用到ElasticSearch(2.3.3),记录一下Elastic的从0开始的使用过程,可以作为入门参考资料。
参考
官网:https://www.elastic.co/products/elasticsearch
安装
机器首先需要安装Java,我的机器已经安装了Java7,这里不赘述。
下载ES并解压到一个目录,比如/opt/es/(以下用path代替),解压完毕,ES就算安装完成了,就可以启动工作了。
我们可以执行 elasticsearch -d,启动ES。
启动之后,在浏览器输入:http://ip:port,会看到提示文本如下,则代表es启动成功。port默认是9200.
脚本
为了方便的启动、停止、修改ES配置,可以制作几个shell脚本。
启动脚本(esstart):
path/elasticsearch-2.3.3/bin/elasticsearch -d
停止脚本(esstop):
kill $(ps -ef | grep elasticsearch | gawk '$0 !~/grep/ {print $2}' |tr -s '\n' ' ')
打开配置文件脚本(esconfig):
vim path/elasticsearch-2.3.3/config/elasticsearch.yml
优雅重启脚本(es-restart-graceful):
#!/bin/bash
ES_SERVER=SERVER_IP
ES_HTTP_PORT=8411
ES_NODE=NODE-XXX
ES_PID=$(ps -ef | grep elasticsearch | gawk '$0 !~/grep/ {print $2}' |tr -s '\n' ' ')
if [ ! $ES_PID ]; then
echo -e '\nElasticSearch Process Not Exists, Exit!'
exit
fi
echo -e "\n"
echo -e "1,Disable shard allocation...\n"
curl -XPUT "http://$ES_SERVER:$ES_HTTP_PORT/_cluster/settings" -d '
{
"transient" : {
"cluster.routing.allocation.enable" : "none"
}
}
'
echo -e "\n"
echo -e "2,shutdown elasticsearch now...\n"
kill $ES_PID
sleep 3
echo -e "3,shutdown elasticsearch complete...\n"
echo -e "4,start elasticsearch now...\n"
cd /opt/meituan/mobile/elasticsearch-2.3.3/
./bin/elasticsearch -d
declare STATUS_CODE=`curl -I -m 10 -o /dev/null -s -w %{http_code} http://$ES_SERVER:$ES_HTTP_PORT/`
declare -i COUNT=0
while [[ $STATUS_CODE != 200 ]] && [[ $COUNT < 10 ]]
do
echo -e "waiting es server to start,time $COUNT..."
COUNT=$COUNT+1
STATUS_CODE=`curl -I -m 10 -o /dev/null -s -w %{http_code} http://$ES_SERVER:$ES_HTTP_PORT/`
sleep 5
done
echo -e "curl http://$ES_SERVER:$ES_HTTP_PORT is ok"
echo -e "\n"
echo -e "5,start elasticsearch complete...\n"
echo -e "6,Enable shard allocation...\n"
curl -XPUT "http://$ES_SERVER:$ES_HTTP_PORT/_cluster/settings" -d '
{
"transient" : {
"cluster.routing.allocation.enable" : "all"
}
}
'
echo -e "\n"
echo -e "7,restart complete!!!\n"
配置
如果是集群,配置:discovery.zen.ping.unicast.hosts: ["ip1", "ip2"]
如果是6个机器:可以配置Shards为6或者12
参考:http://rockelixir.iteye.com/blog/1883373
修改bin/elasticsearch.in.sh,优化JVM内存,比如:
# self-define param begin
export JAVA_OPTS="-Xss256k -XX:+PrintGCDateStamps "
export ES_HEAP_SIZE=2g
export ES_HEAP_NEWSIZE=700m
# self-define param end
插件
常用插件:KOPF、HEAD、SQL。
PATH/elasticsearch-2.3.3/bin/plugin install mobz/elasticsearch-head
PATH/elasticsearch-2.3.3/bin/plugin install lmenezes/elasticsearch-kopf
https://github.com/NLPchina/elasticsearch-sql
另外使用ES必须学会Chrome Sense插件,使用REST方式查询ES集群。
操作
使用restful,比如jest,然后用freemarker之类工具读取查询json,是使用比较方便的方式。
使用es官方的客户端,使用tcp协议,通过bulk操作,是最高效的方式。用这种方式时,比如tcp连接的目标机器是一个列表,比如:10.32.114.170:8419,10.32.107.143:8419,如果1台机器当机,不影响使用。
自己封装一个EsHelper,避免写大量的json查询语句,也很方便。