# Nested内のオブジェクト数で絞り込みする方法について

**URL:** <https://discuss.elastic.co/t/nested/207430>\
**Category:** 日本語による質問・議論はこちら\
**Created:** [November 12, 2019, 2:13am UTC](https://discuss.elastic.co/t/nested/207430 "2019-11-12T02:13:32Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![tsgkdt](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/tsgkdt/32/39151_2.png) [@tsgkdt](https://discuss.elastic.co/u/tsgkdt)\
**Post date:** [November 12, 2019, 4:44am UTC](https://discuss.elastic.co/t/nested/207430/2 "2019-11-12T04:44:42Z")

</div>

Script Queryで頑張ろうとするのは少々しんどそうでしたので、代わりの案を紹介したいです。

> [@Access nested array objects in script query](https://discuss.elastic.co/t/access-nested-array-objects-in-script-query/168461/2):
>
> Have you thought of using an ingest processor that checks the value height and width at index time and stores the result in another field? Then you would have fast queries as you do not need to run an expensive script query at all. Of course this only makes sense if you have a limited number of such checks. --Alex

似たような例がありました。  
[@spinscale](https://discuss.elastic.co/u/spinscale) さんがいうには、オブジェクト数ならオブジェクト数を別フィールドに格納しておけば、より速いクエリが使えるし、コストの高いクエリ（＝Scriptクエリ）を使う必要はない、と書かれています。

今回の例ですと、このようにアプローチするのはダメでしょうか？

↓ userオブジェクト部分の数え上げと、別フィールドに値を格納するパイプラインを作成

```auto
PUT _ingest/pipeline/my_pipeline
{
    "description": "count user nested object size",
    "processors": [
      {
        "script": {
          "source": """
            if (ctx.user != null) {
              ctx.user_count = ctx.user.size();  
            }
            
          """
        }
      }
    ]
}

```

ドキュメント登録時に、パイプラインを指定して登録する。

```auto
PUT my_index/_doc/1?pipeline=my_pipeline
{
  "user" : [
    {
      "first" : "John",
      "last" : "Smith"
    }
  ]
}

```

作成されるIndexで、user\_countにuserオブジェクトの数（今回は１）が入る。

```auto
{
        "_index" : "my_index",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "user_count" : 1,
          "user" : [
            {
              "last" : "Smith",
              "first" : "John"
            }
          ]
        }
      }

```

このようにしておけば、単純な単一フィールドに対する数値の検索になるため、検索クエリが簡単に作れるかと思います。

Pipelineを使ってuser\_count部分を追加しているのは、既存のデータ投入部分に大きな変更を入れなくてもよくて、Pipelineを指定するだけの変更でできそう、ということをお伝えしたかったためです。

ご参考になれば幸いです。

---

_[View the full topic](https://discuss.elastic.co/t/nested/207430)._
