一、安装运行
1.首先需要安装Java环境
2.下载
或官网下载www.elastic.co
3.解压
tar -xvf elasticsearch-2.4.3.tar.gz
4.运行
Linux:./bin/elasticsearch
windows:bin\elasticsearch.bat
加上-d参数可以让进程在后台运行
二、与Es通信
1.java api
Node client:加入集群作为一个无数据节点,不保存数据,但知道数据存放位置,可以把请求转发到正确的节点。
Transport client:轻量级的交流方式,不加入集群,只是转发请求到集群中的一个节点。
java client的主版本最好和集群一致。
2.RESTful API with JSON over HTTP
所有语言都可以使用9200接口和ES通信。
curl -X<VERB> '<PROTOCOL>://<HOST>:<PORT>/<PATH>?<QUERY_STRING>' -d '<BODY>'
实例:
curl -XGET 'http://localhost:9200/_count?pretty' -d ' { "query": { "match_all": {} } } '
三、索引一个文件
PUT /megacorp/employee/1
{
"first_name" : "John",
"last_name" : "Smith",
"age" : 25,
"about" : "I love to go rock climbing",
"interests": [ "sports", "music" ]
}
{
"first_name" : "John",
"last_name" : "Smith",
"age" : 25,
"about" : "I love to go rock climbing",
"interests": [ "sports", "music" ]
}
megacorp
The index name
employee
The type name
1
The ID of this particular employee
四、获取一个索引文件
GET
/
megacorp
/
employee
/
1
五、查询
GET
/
megacorp
/
employee
/
_search
默认返回顶端的10条数据。
加筛选条件:
GET
/
megacorp
/
employee
/
_search
?
q
=
last_name
:
Smith
六、Query DSL(
domain-specific language)
实例:
GET /megacorp/employee/_search
{
"query" : {
"match" : {
"last_name" : "Smith"
}
}
}
{
"query" : {
"match" : {
"last_name" : "Smith"
}
}
}
七、全文查找
GET
/
megacorp
/
employee
/
_search
{
"query" : {
"match" : {
"about" : "rock climbing"
}
{
"query" : {
"match" : {
"about" : "rock climbing"
}
}
}
对查找文本分词为“
rock ”和“
climbing ”对about字段查找。返回的匹配中有_score关键字,它的值是计算文档的相关性值。从大到小倒排。
八、短语查询
GET
/
megacorp
/
employee
/
_search
{
"query" : {
"match_phrase" : {
"about" : "rock climbing"
}
{
"query" : {
"match_phrase" : {
"about" : "rock climbing"
}
}
}
不对查找文本处理,当成一个整体对about字段查找。
九、高亮查询
GET /megacorp/employee/_search
{
"query" : {
"match_phrase" : {
"about" : "rock climbing"
}
},
"highlight": {
"fields" : {
"about" : {}
}
}
{
"query" : {
"match_phrase" : {
"about" : "rock climbing"
}
},
"highlight": {
"fields" : {
"about" : {}
}
}
}
返回中每个文档会多一个highlight项,about字段在其中,匹配的文本都被<em></em>包裹。
十、分析数据
GET /megacorp/employee/_search
{
"aggs": {
"all_interests": {
"terms": { "field": "interests" }
}
}
}
{
"aggs": {
"all_interests": {
"terms": { "field": "interests" }
}
}
}
对interests聚合。