elasticsearch 获取ElastcSearch索引中存在的匹配嵌套对象的总数

nxowjjhe  于 2023-03-29  发布在  ElasticSearch
关注(0)|答案(1)|浏览(138)

考虑下面的示例,其中我有一个带有嵌套字段的索引

{
  "mappings": {
    "properties": {
      "class": {
        "type": "text"
      },
      "subject": {
        "type": "nested",
        "properties": {
          "name": {
            "type": "text"
          }
        }
      }
    }
  }
}

然后我把一些文件编入索引

PUT test_aggs/_doc/1
{
  "class": "first standard",
  "subject": [
    {
      "name": "english basics"
    },
    {
      "name": "maths basics"
    }
    ]
}

PUT test_aggs/_doc/2
{
  "class": "second standard",
  "subject": [
    {
      "name": "english advanced"
    },
    {
      "name": "maths advanced"
    }
    ]
}

PUT test_aggs/_doc/3
{
  "class": "THIRD standard",
  "subject": [
    {
      "name": "english"
    },
    {
      "name": "c programing"
    },
    {
      "name": "maths"
    }
    ]
}

PUT test_aggs/_doc/4
{
  "class": "fourth standard",
  "subject": [
    {
      "name": "social science"
    },
    {
      "name": "java"
    },
    {
      "name": "science"
    }
    ]
}

现在,我想获取主题名称(subject.name字段)中包含英语的所有嵌套对象。

GET test_aggs/_search
{
  "_source": ["class"], 
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "subject",
            "query": {
              "match": {
                "subject.name": "english"
              }
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "subjects": {
      "nested": {
        "path": "subject"
      },
      "aggs": {
        "matched_subject": {
          "filter": {
            
            "match": {
              "subject.name": 
                "english"
            }
          }
        }
      }
    }
  }
}

但是它比较慢。那么还有其他方法来实现我的用例吗?
我的用例是,我只想获得为查询匹配的嵌套对象的总数。
谢谢大家!

a64a0gku

a64a0gku1#

是否可以发送单独查询获取对象结果并相应计数?
仅将聚合用于获取嵌套计数

GET test_aggs/_search
{
  "size": 0,
  "aggs": {
    "subjects": {
      "nested": {
        "path": "subject"
      },
      "aggs": {
        "matched_subject": {
          "filter": {
            "match": {
              "subject.name": "english"
            }
          }
        }
      }
    }
  }
}

使用普通查询得到结果

GET test_aggs/_search
{
  "_source": ["class"], 
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "subject",
            "query": {
              "match": {
                "subject.name": "english"
              }
            }
          }
        }
      ]
    }
  }
}

如果用例只是获取匹配的嵌套对象的总数,那么第一个查询将起作用。

相关问题