一.安装
elasticSearch需要安装jdk1.8才能运行,先执行java -version确保已安装好。
接下来可以顺序执行:(以Centos7安装为例)
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.5.1.zip
unzip elasticsearch-5.5.1.zip
cd elasticsearch-5.5.1/
接下来可以启动执行es:
./bin/elasticsearch
如果安装启动过程中出现问题,请参考https://www.cnblogs.com/yufeng218/p/8331438.html解决。
es默认是在系统的9200端口启动,如果启动正常,则执行以下命令curl localhost:9200可以显示如下信息:
{
"name" : "EZ0OrVD",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "PxNXtH7cRbu8jSBmmpMxpg",
"version" : {
"number" : "5.5.1",
"build_hash" : "19c13d0",
"build_date" : "2017-07-18T20:44:24.823Z",
"build_snapshot" : false,
"lucene_version" : "6.6.0"
},
"tagline" : "You Know, for Search"
}
上述对象返回一个json字符串,包含当前节点名,集群,版本等信息。
二.基本命令
1.Elastic节点
Elastic 本质上是一个分布式数据库,允许多台服务器协同工作,每台服务器可以运行多个 Elastic 实例。
单个 Elastic 实例称为一个节点(node)。一组节点构成一个集群(cluster)
2.Index
Elastic 会索引所有字段,经过处理后写入一个反向索引(Inverted Index)。查找数据的时候,直接查找该索引。
所以,Elastic 数据管理的顶层单位就叫做 Index(索引)。它是单个数据库的同义词。每个 Index (即数据库)的名字必须是小写。
3.Document
Index里单条记录称为Document,许多条 Document 构成了一个 Index。Document不要求有相同的结构(scheme),但是最好保持相同,这样有利于提高搜索效率。
4.Document 可以分组,比如weather
这个 Index 里面,可以按城市分组(北京和上海),也可以按气候分组(晴天和雨天)。这种分组就叫做 Type,它是虚拟的逻辑分组,用来过滤 Document。使用curl 'localhost:9200/_mapping?pretty=true'可以列出每个Index中包含的Type。
三.基本操作命令
新建和删除Index:
curl -X PUT 'localhost:9200/person'
curl -X DELETE 'localhost:9200/person'
新增一条数据:
curl -X PUT 'localhost:9200/accounts/person/1' -d '
{
"user": "张三",
"title": "工程师",
"desc": "数据库管理"
}'
服务器会返回Json对象,会给出Index,Type,Id,Version等信息。
{"_index":"accounts",
"_type":"person",
"_id":"1",
"_version":4,
"result":"updated",
"_shards":
{
"total":2,
"successful":1,
"failed":0
},
"created":false
}
查看记录:
使用命令:curl 'localhost:9200/accounts/person/1?pretty=true'
返回数据中,found表示是否成功,_source表示返回的原始数据。
{
"_index" : "accounts",
"_type" : "person",
"_id" : "1",
"_version" : 4,
"found" : true,
"_source" : {
"user" : "张三",
"title" : "工程师",
"desc" : "数据库管理"
}
}
删除记录:
curl -X DELETE 'localhost:9200/accounts/person/1'
更新记录:
curl -X PUT 'localhost:9200/accounts/person/1' -d '
{
"user" : "张三",
"title" : "工程师",
"desc" : "数据库管理,软件开发"
}
返回所有记录:
curl ‘localhost:9200/accounts/person/_search'
全文检索:
curl 'localhost:9200/accounts/person/_search' -d '
{
"query" : { "match" : { "desc" : "软件" }}
}'
指定match为所搜匹配条件。也可以通过size改变返回的结果数。
curl 'localhost:9200/accounts/person/_search' -d '
{
"query" : { "match" : { "desc" : "软件" }},
“size”:1
}'