2016-01-08 39 views
0

我正在使用Elasticsearch來查找我的結果。我如何在查詢中添加兩個字段?如何在彈性搜索中的bool查詢內求和兩個字段?

{ 
    "query": { 
    "bool": { 
     "must": [ 
     { "term": { "x.flag1": "false" } }, 
     { "term": { "x.flag2": "false" } } 
     ] 
    } 
    } 
} 

現在我想找到兩個領域x.ax.b的總和並將其與其他領域相比,說x.c

(x.a + x.b === x.c) 

我必須包括這個布爾查詢中。所以只有那些滿足這些條件的記錄纔會出現在我的結果中。這可能嗎?

回答

0

您可以通過script query這樣做:

爲ES 2.x的起查詢:

{ 
    "query": { 
    "bool": { 
     "must": [ 
     { 
      "term": { 
      "x.flag1": "false" 
      } 
     }, 
     { 
      "term": { 
      "x.flag2": "false" 
      } 
     } 
     ], 
     "filter": { 
     "script": { 
      "script": "doc['x.a'].value + doc['x.b'].value === doc['x.c'].value" 
     } 
     } 
    } 
    } 
} 

爲2.0之前的ES版同樣的查詢:

{ 
    "query": { 
    "filtered": { 
     "filter": { 
     "bool": { 
      "must": [ 
      { 
       "term": { 
       "x.flag1": "false" 
       } 
      }, 
      { 
       "term": { 
       "x.flag2": "false" 
       } 
      }, 
      { 
       "script": { 
       "script": "doc['x.a'].value + doc['x.b'].value === doc['x.c'].value" 
       } 
      } 
      ] 
     } 
     } 
    } 
    } 
} 

請注意,您需要enable dynamic scripting才能正常工作(即script.inline: true)。

但是,如果您有很多文檔,這可能會使您的ES集羣迅速變慢。如果可能的話,這應該在索引時完成,在那裏您將創建另一個布爾型字段,然後您可以根據包含您需要的true/false條件的布爾字段來簡單地過濾文檔。

+0

Thanks.Let me try。 –

+0

:QueryParsingException [[dooht] [bool]查詢不支持[filter]];我得到這個錯誤怎麼辦? –

+0

你是否在2.0以前的版本中? – Val