elasticsearch,Mapping,elasticsearch" /> elasticsearch,Mapping,elasticsearch" />

Mapping 仅检索数组elasticsearch中的一个对象

Mapping 仅检索数组elasticsearch中的一个对象,mapping,elasticsearch,Mapping,elasticsearch,我有一个名为books的索引,它将评论作为一个对象,可以处理数组。 在检索数据时,在特定情况下,我只希望review具有最大评级 "books" :{ "reviews": { "properties": { "rating": { "type": "float" }, "comments": { "type": "string"

我有一个名为
books
索引
,它将
评论
作为一个
对象
,可以处理数组。 在检索数据时,在特定情况下,我只希望
review
具有最大
评级

"books" :{ 
    "reviews": {
        "properties": {
            "rating": {
                "type": "float"
             },
            "comments": {
                "type": "string"
             }
         }
     },
    "author" : {
        "type" : "string"
    }
 }
许多书可以有许多
评论
,每个都有一些
评级
。对于一个特定的用例,我只希望结果集有
评论
的最大
评分
。我需要为这种结果建立一个搜索
查询

POST books/_search
{
    "size": 51,

    "sort": [
   {
      "reviews.rating": {
         "order": "asc",
         "mode" : "min"
      }
   }
],
"fields": [
   "reviews","author"]
}

通过使用
script\u字段
可以构建动态
字段
,但不能构建
对象
。否则,我可以创建一个动态对象
reviews
,其中一个字段为
评级
,另一个字段为
注释

脚本
可以用于构建动态字段和对象:

curl -XDELETE localhost:9200/test-idx
curl -XPUT localhost:9200/test-idx -d '{
    "mappings": {
        "books" :{ 
            "reviews": {
                "properties": {
                    "rating": {
                        "type": "float"
                     },
                    "comments": {
                        "type": "string"
                     }
                 }
             },
            "author" : {
                "type" : "string"
            }
        }
    }
}'

curl -XPOST "localhost:9200/test-idx/books?refresh=true" -d '{
    "reviews": [{
        "rating": 5.5,
        "comments": "So-so"
    }, {
        "rating": 9.8,
        "comments": "Awesome"
    }, {
        "rating": 1.2,
        "comments": "Awful"
    }],
    "author": "Roversial, Cont"
}'

curl "localhost:9200/test-idx/books/_search?pretty" -d '{
    "fields": ["author"],
    "script_fields": {
        "highest_review": {
            "script": "max_rating = 0.0; max_review = null; for(review : _source[\"reviews\"]) {  if (review.rating > max_rating) { max_review = review; max_rating = review.rating;}} max_review"
        }
    }
}'

我看不到用统计方面来实现这一点的方法。我误解了你的问题,以为你只是需要所有书籍的最高评分。因此,我删除了我的答案。