一共有两种方法,一种是exist查询,一种是判断数组的长度script查询 假如我们有一个字段是
使用exist查询
使用 exists 查询和 nested 查询的结合。
以下是一个示例查询的请求体:
{
"query": {
"nested": {
"path": "<nested_field_path>",
"query": {
"exists": {
"field": "<nested_field_path>"
}
}
}
}
}
将 <nested_field_path>
替换为实际的嵌套字段路径。
这个查询通过 nested
查询指定了嵌套字段的路径,并在其中使用 exists
查询来检查该嵌套字段是否存在。如果存在嵌套字段数据,则满足查询条件。
使用script查询
使用脚本查询来检查 Elasticsearch 中是否存在 nested 类型字段数据。
需要在mapping设置nested类型字段的include_in_parent
为true
例如
"nested_field_path": {
"type": "nested",
"include_in_parent": true, //默认为false
"properties": {
"id": {
"type": "keyword"
}
}
}
}
include_in_parent 是 nested 类型字段的一个属性,它用于指定是否将嵌套字段的值也包含在其父文档中。当 include_in_parent 设置为 true 时,嵌套字段的值将同时存储在子文档中和父文档中,这样可以方便地通过父文档查询来获取嵌套字段的值。当 include_in_parent 设置为 false 时,嵌套字段的值仅存储在子文档中,父文档中不包含该字段的值。 使用 include_in_parent 属性可以根据实际需求来决定是否需要在父文档中包含嵌套字段的值。如果你需要频繁地查询嵌套字段的值,并且对存储空间没有过多的限制,那么可以将 include_in_parent 设置为 true。如果你对存储空间有较高的要求,或者很少需要通过父文档查询嵌套字段的值,那么可以将 include_in_parent 设置为 false,以减少存储空间的占用。 可以使用脚本查询语法。
以下是一个示例查询的请求体:
{
"query": {
"bool": {
"must": [
{
"script": {
"script": {
"source": "doc['<nested_field_path>'].size() > 0",
"lang": "painless"
}
}
}
]
}
}
}
请将 <nested_field_path>
替换为实际的嵌套字段路径。
在该查询中,使用了 script
查询来执行自定义的脚本。脚本内容是通过 doc['<nested_field_path>'].size() > 0
来检查指定嵌套字段的大小是否大于0。如果嵌套字段存在且不为空数组,则满足查询条件。
嵌套nested写法
例如nested里面还有nested
例如:
字段是orderServiceRecordList.completionPictureList,orderServiceRecordList和completionPictureList都是nested类型,怎么查询completionPictureList不为空数组的数据
解答:
要查询 orderServiceRecordList.completionPictureList
字段不为空数组的数据,使用 Elasticsearch 的 nested
查询和 exists
查询的组合。下面是一个示例查询:
{
"query": {
"nested": {
"path": "orderServiceRecordList",
"query": {
"nested": {
"path": "orderServiceRecordList.completionPictureList",
"query": {
"exists": {
"field": "orderServiceRecordList.completionPictureList"
}
}
}
}
}
}
}
在这个查询中,首先使用外部的 nested
查询指定了 orderServiceRecordList
字段的路径。然后,在内部的 nested
查询中,我们指定了 orderServiceRecordList.completionPictureList
字段的路径,并使用 exists
查询来检查该字段是否存在。
评论区