版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013219624/article/details/84777333
0.数据准备
# text指定中文分词器(ik_max_word)
PUT data
{
"settings": {
"number_of_replicas": 0,
"number_of_shards": 3
},
"mappings": {
"user": {
"properties": {
"name":{"type":"text","analyzer":"ik_max_word"},
"age":{"type":"integer"},
"address":{"type":"text","analyzer":"ik_max_word"},
"interests":{"type":"text","analyzer":"ik_max_word"},
"birthday":{"type":"date"}
}
}
}
}
PUT data/user/1
{
"name":"赵六",
"address":"北京市西二旗",
"age":23,
"birthday":"1995-10-11",
"interests":"吃鸡 英雄联盟 王者荣耀"
}
PUT data/user/2
{
"name":"王五",
"address":"上海市徐家汇",
"age":13,
"birthday":"2005-08-15",
"interests":"吃鸡 唱歌 王者荣耀"
}
PUT data/user/3
{
"name":"赵四",
"address":"南京市雨花台",
"age":18,
"birthday":"2000-01-01",
"interests":"吃鸡 唱歌 王者荣耀"
}
PUT data/user/4
{
"name":"张三",
"address":"无锡市太湖",
"age":18,
"birthday":"2001-11-09"
}
注:常用中文分词器ik_max_word ik_smart
1.filter查询(不计算相关性;可以cache;比query快)
GET data/user/_search
{
"query": {
"bool": {
"filter": {
"terms": {
"age": [23, 18]
}
}
}
}
}
GET data/user/_search
{
"query": {
"bool": {
"should":[
{"term":{"age":23}},
{"term":{"name":"赵"}}
],
"must_not": [
{"term":{"age":18}}
]
}
}
}
注:bool过滤查询 must相当于and should相当于or must_not相当于!=
GET data/user/_search
{
"query": {
"bool": {
"filter": {
"range": {
"age": {
"gt": 13,
"lte": 18
}
}
}
}
}
}
注:gt(>) gte(>=) lt(<) lte(<=)
GET data/user/_search
{
"query": {
"bool": {
"filter": {
"exists": {
"field": "interests"
}
}
}
}
}
注:exists不为null
2.聚合查询
# 求和
GET data/user/_search
{
"size": 0,
"aggs": {
"age_of_sum": {
"sum": {
"field": "age"
}
}
}
}
# 取最小值
GET data/user/_search
{
"size": 0,
"aggs": {
"min_of_age": {
"min": {
"field": "age"
}
}
}
}
# 取最大值
GET data/user/_search
{
"size": 0,
"aggs": {
"max_of_age": {
"max": {
"field": "age"
}
}
}
}
# 取平均值
GET data/user/_search
{
"size": 0,
"aggs": {
"age_of_avg": {
"avg": {
"field": "age"
}
}
}
}
# 求基数
GET data/user/_search
{
"size": 0,
"aggs": {
"age_of_cardinality": {
"cardinality": {
"field": "age"
}
}
}
}
# 分组(相当于group)
GET data/user/_search
{
"size": 0,
"aggs": {
"price_of_group": {
"terms": {
"field": "age"
}
}
}
}
# 有唱歌兴趣的用户 按年龄分组
GET data/user/_search
{
"query": {
"match": {
"interests": "唱歌"
}
},
"aggs": {
"age_of_group": {
"terms": {
"field": "age"
}
}
}
}
3.复合查询
GET data/user/_search
{
"query": {
"bool": {
"should": [
{
"match": {
"name": "赵"
}
},
{
"bool": {
"should": [
{
"terms": {
"age": [13]
}
}
]
}
}
],
"must_not": [
{
"term": {
"age": 18
}
}
]
}
}
}
4.constant_score, 不计算scope值
GET data/user/_search
{
"query": {
"constant_score": {
"filter": {
"terms": {
"age": [
18,
23
]
}
}
}
}
}