Elasticsearchにネストされたフィールドで独自のドキュメントの数をカウントするには?

user2220154:

私は(も、次の、文書自体)のユニークなネストされたフィールドの値を持つ文書をカウントしようとしています。ユニークなドキュメント作品を得るように見えます。私は要求を実行しようとしているときにはcount、次のように、私はエラーを取得しています:

抑制:org.elasticsearch.client.ResponseException:メソッド[POST]、ホスト[ のhttp:// localhostを:9200]、URI [/パッケージ/ _count ignore_throttled =真&ignore_unavailable =偽&expand_wildcards =オープン&allow_no_indices =本当?]、ステータスライン[HTTP / 1.1を400不正なリクエスト] { "エラー":{ "ROOT_CAUSE":[{ "タイプ": "parsing_exception"、 "理由": "要求が[崩壊をサポートしていない]"、 "行":1、 "COL":216} ]、 "タイプ": "parsing_exception"、 "理由": "要求が[崩壊]をサポートしていない"、 "行":1、 "COL":216}、 "ステータス":400}

コード:

        BoolQueryBuilder innerTemplNestedBuilder = QueryBuilders.boolQuery();
        NestedQueryBuilder templatesNestedQuery = QueryBuilders.nestedQuery("attachment", innerTemplNestedBuilder, ScoreMode.None);
        BoolQueryBuilder mainQueryBuilder = QueryBuilders.boolQuery().must(templatesNestedQuery);
        if (!isEmpty(templateName)) {
            innerTemplNestedBuilder.filter(QueryBuilders.termQuery("attachment.name", templateName));
        }
        SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource()
                    .collapse(new CollapseBuilder("attachment.uuid"))
                    .query(mainQueryBuilder);
    // NEXT LINE CAUSE ERROR
        long count = client.count(new CountRequest("package").source(searchSourceBuilder), RequestOptions.DEFAULT).getCount(); <<<<<<<<<< ERROR HERE
        // THIS WORKS 
        SearchResponse searchResponse = client.search(
                    new SearchRequest(
                            new String[] {"package"},
                            searchSourceBuilder.timeout(new TimeValue(20, TimeUnit.SECONDS)).from(offset).size(limit)
                    ).indices("package").searchType(SearchType.DFS_QUERY_THEN_FETCH),
                    RequestOptions.DEFAULT
        );
        return ....;

アプローチの全体的な意図は、文書の一部及び全てのそのような文書の数を取得することです。すでに存在しているこのようなニーズのための別のアプローチがあるかもしれません。私が取得しようとしている場合はcount使用aggregationsしてcardinality-私はゼロの結果を取得していますし、それがネストされたフィールド上では動作しませんように見えます。

リクエストを数:

{
    "query": {
        "bool": {
            "must": [
                {
                    "nested": {
                        "query": {
                            "bool": {
                                "adjust_pure_negative": true,
                                "boost": 1.0
                            }
                        },
                        "path": "attachment",
                        "ignore_unmapped": false,
                        "score_mode": "none",
                        "boost": 1.0
                    }
                }
            ],
            "adjust_pure_negative": true,
            "boost": 1.0
        }
    },
    "collapse": {
        "field": "attachment.uuid"
    }
}

どのようにマッピングを作成しました:

curl -X DELETE "localhost:9200/package?pretty"
curl -X PUT    "localhost:9200/package?include_type_name=true&pretty" -H 'Content-Type: application/json' -d '{
    "settings" :  {
        "number_of_shards" : 1,
        "number_of_replicas" : 1
    }}'
curl -X PUT    "localhost:9200/package/_mappings?pretty" -H 'Content-Type: application/json' -d'
{
      "dynamic": false,
      "properties" : {
        "attachment": {
            "type": "nested",
            "properties": {
                "uuid" : { "type" : "keyword" },
                "name" : { "type" : "text" }
            }
        },
        "uuid" : {
          "type" : "keyword"
        }
      }
}
'

コードによって生成された結果クエリは次のようなものでなければなりません。

curl -X POST "localhost:9200/package/_count?&pretty" -H 'Content-Type: application/json' -d' { "query" :
    {
        "bool": {
            "must": [
                {
                    "nested": {
                        "query": {
                            "bool": {
                                "adjust_pure_negative": true,
                                "boost": 1.0
                            }
                        },
                        "path": "attachment",
                        "ignore_unmapped": false,
                        "score_mode": "none",
                        "boost": 1.0
                    }
                }
            ],
            "adjust_pure_negative": true,
            "boost": 1.0
        }
    },
    "collapse": {
        "field": "attachment.uuid"
    }
}'
jzzfs:

折りたたみができるだけ使用することでは_searchないで、コンテキスト_count

第二に、あなたのクエリにも何をするのでしょうか?あなたは次のようにそこに冗長パラメータの多くを持っているboost:1あなたにも言うかもしれないなど。

POST /package/_count?&pretty
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "attachment",
            "query": {
              "match_all": {}
            }
          }
        }
      ]
    }
  }
}

これは本当に何もしません:)


あなたの元の質問に答えるために、「独特のネストされたフィールドの値とカウント文書」のを、

のは、同じ持っている2その3つの文書、想像してみましょうattachment.uuid値:

[
  {
    "attachment":{
      "uuid":"04144e14-62c3-11ea-bc55-0242ac130003"
    }
  },
  {
    "attachment":{
      "uuid":"04144e14-62c3-11ea-bc55-0242ac130003"
    }
  },
  {
    "attachment":{
      "uuid":"100b9632-62c3-11ea-bc55-0242ac130003"
    }
  }
]

取得するtermsの内訳uuid秒、実行を

GET package/_search
{
  "size": 0,
  "aggs": {
    "nested_uniques": {
      "nested": {
        "path": "attachment"
      },
      "aggs": {
        "subagg": {
          "terms": {
            "field": "attachment.uuid"
          }
        }
      }
    }
  }
}

これは利回り

...
{
  "aggregations":{
    "nested_uniques":{
      "doc_count":3,
      "subagg":{
        "doc_count_error_upper_bound":0,
        "sum_other_doc_count":0,
        "buckets":[
          {
            "key":"04144e14-62c3-11ea-bc55-0242ac130003",
            "doc_count":2
          },
          {
            "key":"100b9632-62c3-11ea-bc55-0242ac130003",
            "doc_count":1
          }
        ]
      }
    }
  }
}

ユニークなネストされたフィールドの親ドキュメント数を取得するために、我々はもう少し賢い取得する必要がありますつもりです。

GET package/_search
{
  "size": 0,
  "aggs": {
    "nested_uniques": {
      "nested": {
        "path": "attachment"
      },
      "aggs": {
        "scripted_uniques": {
          "scripted_metric": {
            "init_script": "state.my_map = [:];",
            "map_script": """
              if (doc.containsKey('attachment.uuid')) {
                state.my_map[doc['attachment.uuid'].value.toString()] = 1;
              }
            """,
            "combine_script": """
              def sum = 0;
              for (c in state.my_map.entrySet()) {
                sum += 1
              }
              return sum
            """,
            "reduce_script": """
              def sum = 0;
              for (agg in states) {
                sum += agg;
              }
              return sum;
            """
          }
        }
      }
    }
  }
}

そのリターン

...
{
  "aggregations":{
    "nested_uniques":{
      "doc_count":3,
      "scripted_uniques":{
        "value":2
      }
    }
  }
}

これはscripted_uniques: 2あなたが後にしているまさにです。


注:私はスクリプトネストされたメトリックaggsを使用して、このユースケースを解くが、あなたがたのうち、クリーンなアプローチを知っていれば、私は以上のことを学ぶことが幸せです!

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=283518&siteId=1