针对数组,有没有一种情况,就是在同一个索引下,有时候想交叉搜索扩大搜索范围,有时候又只想搜索属于单个 object 的数据来精确搜索?我们在真实场景遇到。
1.插入一条数据:
PUT /blog/_doc/1
{
"title":"Nest eggs",
"body":"Making your money work...",
"tags":[
"cash",
"shares"
],
"comments":[
{
"name":"John Smith",
"comment":"Great article",
"age":28,
"stars":4,
"date":"2014-09-01"
},
{
"name":"Alice White",
"comment":"More like this please",
"age":31,
"stars":5,
"date":"2014-10-22"
}
]
}
2.按照之前对 nested 的讲解我们用下面搜索是可以搜到的:
POST /blog/_search
{
"query":{
"bool":{
"must":[
{
"match":{
"comments.name":"Alice"
}
},
{
"match":{
"comments.age":28
}
}
]
}
}
}
3.如果我们使用了 nested 之后,我们是搜索不到该文档的:
1).删除之前的索引:
DELETE /blog
2).创建一个nested 字段很简单,只要在你通常指定 object 类型的地方,改成 nested 类型就行:
PUT /blog
{
"mappings": {
"properties": {
"title": {
"type": "text"
},
"body": {
"type": "text"
},
"tags": {
"type": "keyword"
},
"comments": {
"type": "nested",
"properties": {
"name": {
"type": "text"
},
"comment": {
"type": "text"
},
"age": {
"type": "short"
},
"stars": {
"type": "short"
},
"date": {
"type": "date"
}
}
}
}
}
}
3).插入之前的文档:
PUT /blog/_doc/1
{
"title":"Nest eggs",
"body":"Making your money work...",
"tags":[
"cash",
"shares"
],
"comments":[
{
"name":"John Smith",
"comment":"Great article",
"age":28,
"stars":4,
"date":"2014-09-01"
},
{
"name":"Alice White",
"comment":"More like this please",
"age":31,
"stars":5,
"date":"2014-10-22"
}
]
}
4).再用以前的方法就搜索不到了:
POST /blog/_search
{
"query":{
"bool":{
"must":[
{
"match":{
"comments.name":"Alice"
}
},
{
"match":{
"comments.age":28
}
}
]
}
}
}
4.如果此时我们又想使用该查询语句搜索到该文档,该怎么办呢?也就是在同一个索引下,有时候我想交叉搜索,有时候我只想搜索属于单个 object 的数据,这样的情况该怎么处理?
1).删除之前的索引:
DELETE /blog
2).创建mappings:
PUT /my_index
{
"mappings": {
"blog": {
"properties": {
"title": {
"type": "text"
},
"body": {
"type": "text"
},
"tags": {
"type": "keyword"
},
"comments": {
"type": "nested",
"include_in_parent": true,
"properties": {
"name": {
"type": "text"
},
"comment": {
"type": "text"
},
"age": {
"type": "short"
},
"stars": {
"type": "short"
},
"date": {
"type": "date"
}
}
}
}
}
}
}
3).插入之前的文档:
PUT /blog/_doc/1
{
"title":"Nest eggs",
"body":"Making your money work...",
"tags":[
"cash",
"shares"
],
"comments":[
{
"name":"John Smith",
"comment":"Great article",
"age":28,
"stars":4,
"date":"2014-09-01"
},
{
"name":"Alice White",
"comment":"More like this please",
"age":31,
"stars":5,
"date":"2014-10-22"
}
]
}
4).交叉搜索(扩大搜索范围)可以搜到:
POST /blog/_search
{
"query":{
"bool":{
"must":[
{
"match":{
"comments.name":"Alice"
}
},
{
"match":{
"comments.age":28
}
}
]
}
}
}
5).使用 nested 精确搜索也可以搜到:
GET /blog/_search
{
"query":{
"bool":{
"must":[
{
"match":{
"title":"eggs"
}
},
{
"nested":{
"path":"comments",
"query":{
"bool":{
"must":[
{
"match":{
"comments.name":"john"
}
},
{
"match":{
"comments.age":28
}
}
]
}
}
}
}
]
}
}
}