从ElasticSearch Aggregation中排除nil值

时间:2014-10-06 13:48:15

标签: ruby-on-rails elasticsearch filtering aggregation

我使用此查询来检索最重要的值:

keywords = Answer.search( 
    :size => 5, 
    :query => { 
        :match => {
            :question_id => 32481
         }
    }, 
    :aggregations => { 
        :keywords => { 
            :significant_terms => {
                :field => 'text'
            }
        }
    }
)

字段是:text,但它有nil值,所以答案总是:

2.1.2 :135 > keywords.map(&:text)
=> [nil, nil, nil, nil, nil]

我尝试添加过滤器,如the documentation所示,但它给了我一个解析错误:

keywords = Answer.search( 
    :size => 5, 
    :query => { 
        :match => {
            :question_id => 32481
         },
         :filtered => {
             :filter => {
                 :exists => { :field => 'text' }
             }
         }
    }, 
    :aggregations => { 
        :keywords => { 
            :significant_terms => {
                :field => 'text'
            }
        }
    }
)

我尝试了很多组合,没有成功。我怎样才能得到有效的文字答案?

1 个答案:

答案 0 :(得分:1)

我相信您的ES查询应该转换为以下内容:

  "size": 5,
  "query": {
    "filtered": {
      "query": { "match": { "question_id" : 32481 } },
      "filter": {
        "exists": {
          "field": "text"
        }
      }
    }
  },
  "aggs": {
    "keywords": {
      "significant_terms": {
        "field": "text"
      }
    }
  }

意味着您的“question_id”“匹配”应该包含在“过滤”元素中。