结构化搜索
# 示例数据
POST /my_store/products/_bulk
{ "index": { "_id": 1 }}
{ "price" : 10, "productID" : "XHDK-A-1293-#fJ3" }
{ "index": { "_id": 2 }}
{ "price" : 20, "productID" : "KDKE-B-9947-#kL5" }
{ "index": { "_id": 3 }}
{ "price" : 30, "productID" : "JODL-X-1937-#pV7" }
{ "index": { "_id": 4 }}
{ "price" : 30, "productID" : "QQPX-R-3956-#aD8" }
# 查找价格为20的商品, 价格为数字,精确匹配
GET /my_store/_search
{
"query": {
"term": {
"price": 20
}
}
}
# 精确匹配,使用常量评分,提升效率
GET /my_store/_search
{
"query": {
"constant_score": {
"filter": {
"term": {
"price": 20
}
},
"boost": 1.2
}
}
}
# term查询文本
GET /my_store/_analyze
{
"field": "productID",
"text": ["JODL-X-1937-#pV7"]
}
GET /my_store/_search
{
"query": {
"constant_score": {
"filter": {
"term": {
"productID.keyword": "JODL-X-1937-#pV7"
}
},
"boost": 1.2
}
}
}
# 组合过滤器
# bool过滤器,must、must_not、should
GET /my_store/_search
{
"query": {
"constant_score": {
"filter": {
"bool": {
"should":[
{"term": {"price": 20}},
{"term": {"productID.keyword": "XHDK-A-1293-#fJ3"}}
],
"must_not":[
{"term": {"price": 30}}
]
}
},
"boost": 1.2
}
}
}
# 查找多个精确值
# term和terms是包含操作,并非等值操作
GET /my_store/_search
{
"query" : {
"constant_score" : {
"filter" : {
"terms" : {
"price" : [20, 30]
}
}
}
}
}
GET /my_store/_search
{
"query" : {
"constant_score" : {
"filter" : {
"terms" : {
"productID":["QQPX","r"]
}
}
}
}
}
POST /my_index/posts/_bulk
{ "index": { "_id": "1" }}
{ "tags" : ["search"] }
{ "index": { "_id": "2" }}
{ "tags" : ["search", "open_source"] }
{ "index": { "_id": "3" }}
{ "other_field" : "some data" }
{ "index": { "_id": "4" }}
{ "tags" : null }
{ "index": { "_id": "5" }}
{ "tags" : ["search", null] }
# 处理null值,使用exists查询相当于is not null
# missing 相当于is null
GET /my_index/posts/_search
{
"query": {
"constant_score": {
"filter": {
"exists": {
"field": "tags"
}
},
"boost": 1.2
}
}
}