Elasticsearch Query API
创建索引,并插入数据
1.创建一个索引为users,类型为userinfo的indices
PUT /users/userinfo/1
{
"first_name" : "John",
"last_name" : "Smith",
"age" : 25,
"about" : "I love to go rock climbing",
"interests": [ "sports", "music" ]
}
查询
精准查询
当进行进准查询时,我们会使用过滤器(filters)。过滤器的执行速度非常快,不会计算相关度(直接跳过整个评分阶段)而且很容易被缓存。
非文本查询
GET users/userinfo/_search
{
"query": {
"constant_score": {
"filter": {
"term": {
"_id": "1"
}
},
"boost": 1
}
}
}
constant_score 以非评分模式来执行,并将term查询转化为过滤器
文本查询
1.根据about查询
request
GET users/userinfo/_search
{
"query": {
"constant_score": {
"filter": {
"term": {
"about": "I love to go rock climbing"
}
},
"boost": 1
}
}
}
response
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 0,
"max_score": null,
"hits": []
}
}
可以发现,查询不到任何数据。
2.分析API
request
GET users/_analyze
{
"field": "about"
, "text": ["I love to go rock climbing"]
}
response
{
"tokens": [
{
"token": "i",
"start_offset": 0,
"end_offset": 1,
"type": "",
"position": 0
},
{
"token": "love",
"start_offset": 2,
"end_offset": 6,
"type": "",
"position": 1
},
{
"token": "to",
"start_offset": 7,
"end_offset": 9,
"type": "",
"position": 2
},
{
"token": "go",
"start_offset": 10,
"end_offset": 12,
"type": "",
"position": 3
},
{
"token": "rock",
"start_offset": 13,
"end_offset": 17,
"type": "",
"position": 4
},
{
"token": "climbing",
"start_offset": 18,
"end_offset": 26,
"type": "",
"position": 5
}
]
}
可以得知,es使用了5个token来表示字段,根据倒排索引的原则,自动拆分,并且全部使用小写表示,丢失连字符和哈希符。
3.
聚合运算
1.根据时间,求和
GET syslog_2018.05.03/_search?size=0
{
"aggs": {
"sales_per_month" : {
"date_histogram" : {
"field" : "@timestamp",
"interval" : "5s",
"time_zone": "Asia/Shanghai"
"extended_bounds": {
"min": "now/d",
"max": "now/d"
}
},
"aggs" : {
"sum_price" : {
"sum" : {
"field" : "value"
}
}
}
}
}
}