安装
安装elasticSearch和kibana
简单应用
一个Elasticsearch集群可以包含多个索引(index),相应的每个索引可以包含多个类型(type).这些不同的类型存储着多个文档,每个文档又有多个属性
放入信息
PUT /megacorp/employee/1
{
"first_name" : "John",
"last_name" : "Smith",
"age" : 25,
"about" : "I love to go rock climbing",
"interests": [ "sports", "music" ]
}
PUT /megacorp/employee/2
{
"first_name" : "Jane",
"last_name" : "Smith",
"age" : 32,
"about" : "I like to collect rock albums",
"interests": [ "music" ]
}
PUT /megacorp/employee/3
{
"first_name" : "Douglas",
"last_name" : "Fir",
"age" : 35,
"about": "I like to build cabinets",
"interests": [ "forestry" ]
}
其中megacorp
索引名称,employee
类型名称,1
是特定雇员的ID
检索单个雇员
GET /megacorp/employee/1
返回值,
{
"_index": "megacorp",
"_type": "employee",
"_id": "1",
"_version": 1,
"found": true,
"_source": {
"first_name": "John",
"last_name": "Smith",
"age": 25,
"about": "I love to go rock climbing",
"interests": [
"sports",
"music"
]
}
}
轻量搜素
获取所有雇员
GET /megacorp/employee/_search
查询字符串
GET /megacorp/employee/_search?q=last_name:smith
结果
{
"took": 110,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 2,
"max_score": 0.2876821,
"hits": [
{
"_index": "megacorp",
"_type": "employee",
"_id": "2",
"_score": 0.2876821,
"_source": {
"first_name": "Jane",
"last_name": "Smith",
"age": 32,
"about": "I like to collect rock albums",
"interests": [
"music"
]
}
},
{
"_index": "megacorp",
"_type": "employee",
"_id": "1",
"_score": 0.2876821,
"_source": {
"first_name": "John",
"last_name": "Smith",
"age": 25,
"about": "I love to go rock climbing",
"interests": [
"sports",
"music"
]
}
}
]
}
}
查询的时候,会发现,真实数据中last_name是Simth,都查询出来了,但是有 _score这个标签, _score是一种确定匹配与查询的相关程度的方法.
使用查询表达式搜素
GET /megacorp/employee/_search
{
"query": {
"match": {
"last_name": "smith"
}
}
}
可以发现,和上面的查询是一样的
复杂的搜索
GET /megacorp/employee/_search
{
"query" : {
"bool": {
"must": {
"match" : {
"last_name" : "smith"
}
},
"filter": {
"range" : {
"age" : { "gt" : 30 }
}
}
}
}
}
搜索最后一个名字是smith的,并过滤其中年龄大于30岁的
全文搜索
GET /megacorp/employee/_search
{
"query":{
"match":{
"about": "rock climbing"
}
}
}
可以找到两条,其中一条数据是"about": "I love to go rock climbing"
还有一条是"about": "I like to collect rock albums"
为什么第二条也有呢,因为提到了rock,只是_score相应的低了一点
短语查找
GET /megacorp/employee/_search
{
"query":{
"match_phrase": {
"about": "rock climbing"
}
}
}
可以精确查找