2012-08-08 66 views
1

查詢我有像這樣一些數據elasticsearch:返回一個自定義字段,其中值取決於elasticsearch

account (http://localhost:9200/myapp/account/1) 
======== 
name 
state 
groups //groups is an array containing objects like so {id: 1, starred: true} 
     //the id is the id of the group type 

email (http://localhost:9200/myapp/email/1?parent=1) 
======== 
email 
primary //just a boolean to denote whether this email is primary or not 

group 
======== 
name 
description 

email s爲的account孩子。

基於imotov's excellent answer,我能夠運行在account.nameemail.email搜索,並在搜索前綴匹配以上2場返回所有account S:

{ 
    "query": { 
    "bool": { 
     "must": [ 
     { 
      "term": { 
      "statuses": "active" 
      } 
     } 
     ], 
     "should": [ 
     { 
      "prefix": { 
      "name": "a" 
      } 
     }, 
     { 
      "has_child": { 
      "type": "email", 
      "query": { 
       "prefix": { 
       "email": "a" 
       } 
      } 
      } 
     } 
     ], 
     "minimum_number_should_match" : 1 
    } 
    } 
} 

我想現在是時候做返回2個自定義字段對於每個結果:

  • 對於每個結果返回一個字段稱爲email,如果搜索是在email型匹配(這是子女account),返回該電子郵件,否則返回鏈接到該帳戶的primary電子郵件,如果沒有,則返回null

  • 對於每個結果返回一個稱爲group的字段。該字段的值應包含其標識存儲在groups陣列中的加星號的group的名稱。實質上:查找group.id其中group.starred在每個account.groups中都爲真,然後從group類型的基於我們找到的id返回匹配的group.name

我一直在尋找script fields,但我不確定它是否能夠爲每次打擊返回字段。我也不確定上述內容是否可以在ES中實現。

有人可以提供一些指示,以確定這是否可行以及如何開始?

回答

1

目前,根本無法訪問has_childnested子句中的數據。

唯一的解決方案是獲取一些數據,在客戶端做出一些決定,然後獲得更多的數據。

這裏是我做了什麼來實現它:

  • 運行上面的查詢和找回數據。

  • 爲了應對顯示匹配的電子郵件或主電子郵件(在電子郵件類型運行):

    {"query": 
        {"bool":{ 
         "should":{ 
         { 
          "prefix":{ 
           "email" : "the query" 
          } 
         }, 
         { 
          "terms":{ 
           "_parent" : ["list", "of", "account", "ids"] 
          } 
         } 
         } 
        } 
        } 
    } 
    

基於以上的查詢,我們可以得到被匹配的任何電子郵件地址搜索詞。請記住設置上述查詢中的字段以包含_parent

然後,我們可以使用array_diff()或PHP以外的其他語言的類似函數來區分上方和下方的父ID和原始查詢。然後,這應該給我們一個沒有電子郵件匹配的帳戶列表。只需發送另一個請求即可獲取這些帳戶的主要電子郵件。

對於組,將查詢發送到輸入account和:

  • 約束_id到帳戶ID列表。
  • 約束group.starredtrue

這應該爲您提供加星標組的列表。爲了獲得更多的信息(姓名等),將查詢發送到輸入group和:

  • 約束_id到組以上的ID。

最後,做一些客戶端處理將它放在一起,以便您的程序的下一部分更容易使用。

相關問題