仅检索数组elasticsearch内的一个对象

时间:2013-12-04 07:17:56

标签: mapping elasticsearch

我有一个名为index的{​​{1}},其booksreviews,可以处理数组。 在检索数据时,在特定情况下,我只希望object具有最大review

rating

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

query

使用POST books/_search { "size": 51, "sort": [ { "reviews.rating": { "order": "asc", "mode" : "min" } } ], "fields": [ "reviews","author"] } 可以构建动态script_fields但不能构建fields。另外,我可以制作一个动态对象objects,其中一个字段为reviews,另一个字段为rating

1 个答案:

答案 0 :(得分:2)

script_fields可用于构建动态字段和对象:

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"
        }
    }
}'