环境
- ElasticSearch6.4.2
- 以下查询请求方式均为Post
- 索引名:book
- 索引结构:
{
"mappings": {
"novel": {
"properties": {
"word_count": {
"type": "interger"
},
"author": {
"type": "keyword"
},
"title": {
"type": "text"
},
"publish_date": {
"format": "yyyy-MM-dd HH:mm:ss||yyy-MM-dd||epoch_mills",
"type": "date"
}
}
}
}
}
基本查询
查询全部
form指定从哪里返回
size指定返回数量
{
"query": {
"match_all": {}
}
"from": 1
"size": 1
}
关键词查询
- url:~/_search
- 在title中匹关键词joker, 并按照出场日期的降序排序
{
"query": {
"match": {
"title": "joker"
},
"sort": [
{"publish_date":{"order":"desc}}
]
}
}
聚合查询
- 分别根据word_count字段和publish_date字段分组聚合查询,实际上就是统计同样字数的有几本书,同样出版日期的又有几本书。
{
"aggs": {
"group_by_word_count": {
"terms": {
"field": "word_count"
}
},
"group_by_publish_date": {
"term": {
"field": "publish_date"
}
}
}
}
- 计算word_count字段的总数,最小值,最大值,平均值,总和。
- 分别对应count,min,max,avg,sum。将stats替换为以上单词则查询只对应结果。
{
"aggs": {
"grades_word_count": {
"stats": {
"field": "word_count"
}
}
}
}
高级查询
子条件查询
特定字段查询所指特定值
Query Context
会根据匹配程度生成不同的匹配分数
全文本查询 针对文本类型
- 模糊匹配
- 根据title模糊匹配“ElasticSearch入门”
{
"query": {
"match": {
"title": "ElasticSearch入门"
}
}
}
- 词语匹配
- 把“ElasticSearch入门”当作一个词语匹配
{
"query": {
"match_phrase": {
"title": "ElasticSearch入门"
}
}
}
- 多个字段模糊匹配查询
- 在author和title字段中模糊匹配joker
- 适用于单关键词多字段查询
{
"query": {
"multi_match": {
"query": "joker"
"fields": ["author", "title"]
}
}
}
- 语法查询
- 在title和author字段中匹配,其中某个字段需同时含有‘ElasticSearch’和’大法’,或者含有’Python’
- 适用于多关键词多字段查询
{
"query": {
"query_string": {
"query": "(ElasticSearch AND 大法) OR Python",
"fields": ["title", "author"]
}
}
}
字段级别查询 针对结构化数据:数字,日期等。
{
"query": {
"term": {
"word_count": 1000
}
}
}
- 查询字段word_count大于等于1000小于2000的数据
{
"query": {
"range": {
"word_count": {
"gte": 1000,
"lg": 2000
}
}
}
}
- 查询字段publish_date从2018-1-1到现在的的数据
{
"query": {
"range": {
"publish_date": {
"gte": "2018-1-1",
"lg": "now"
}
}
}
}
Filter Context
只判断该文档是否满足条件,只有是或者不是
而且Filter的结果会加入缓存,比Query快一些
{
"query": {
"bool": {
"filter": {
"term": {
"word_count": 1000
}
}
}
}
}
常用复合条件查询
以一定的逻辑组合子条件查询
- 固定分数查询
模糊匹配ElasticSearch, 查询出所有匹配分数都为2,由boost指定,默认为1
只支持Filter查询
{
"query": {
"constant_score": {
"filter": {
"match": {
"title": "ElasticSearch"
}
}
},
"boost": 2
}
}
- 布尔查询
should是模糊匹配,must, must_not为精确匹配
filter指定过滤条件,word_count必须为1000
{
"query": {
"bool": {
"must": [
{
"match": {
"title": "joker"
},
"match": {
"title": "ElasticSearch"
}
}
],
"filter": [
"term": {
"word_count": 1000
}
]
}
}
}