2015-10-30 95 views
0

我爲我的Ruby on Rails應用程序使用elasticsearch-railselasticsearch-model寶石,這就像問答網站。在嵌套對象更新上更新多個文檔

我的主要問題是:當嵌套在多個文檔中的嵌套對象發生更改時,如何告知Elasticsearch要更新哪些文檔?

我有一個索引my_index和映射questionanswer。特別是,question有一個user嵌套對象:

"question": { 
    "properties": { 
     "user": { 
     "type": "nested", 
     "properties": { 
      "created_at": { 
       "type": "date", 
       "format": "dateOptionalTime" 
      }, 
      "name": { 
       "type": "string" 
      }, 
      "id": { 
       "type": "long" 
      }, 
      "email": { 
       "type": "string" 
      } 
      } 
     } 
     ... 
    } 
} 

這有可能爲用戶更改他的名字,我有鉤更新Elasticsearch用戶:

after_commit lambda { __elasticsearch__.index_document}, on: :update 

但這ISN不正確地更新適當的question對象,我不知道要傳遞給index_document調用的內容,以確保它使用新的用戶名更新所有相應的question。有人知道嗎?它甚至可以幫助我看看RESTful/curl請求應該是什麼樣子?

任何幫助,將不勝感激!

回答

0

有幾種不同的方法可以解決這個問題。不過,它們都可能需要更改代碼。我不認爲有一種方法可以根據您當前的設置直接詢問您的問題。

您可以閱讀關於各種選項here。如果你能把事情設置成一對多的關係,那麼parent/child relationship可能就是要走的路。然後,你可以建立這樣的事情:

PUT my_index 
{ 
    "mappings": { 
     "user": { 
     "properties": {...} 
     }, 
     "question": { 
     "_parent": { 
      "type": "user" 
     }, 
     "properties": {...} 
     } 
    } 
} 

而且在這種情況下,你就可以單獨更新usersquestions。但它使查詢更復雜,這可能會或可能不會成爲您的應用程序代碼中的問題。

既然你設置已經嵌套的文件,你可以簡單地查詢所有具有特定用戶爲嵌套文件的文件,喜歡的東西:

POST /test_index/question/_search 
{ 
    "filter": { 
     "nested": { 
     "path": "user", 
     "filter": { 
      "term": { 
       "user.id": 2 
      } 
     } 
     } 
    } 
} 

,一旦你擁有所有的影響question文檔,您可以修改每個文檔中的用戶名,並使用bulk index請求更新所有文檔。

下面是一些代碼我用來玩的最後一點:

http://sense.qbox.io/gist/d2a319c6b4e7da0d5ff910b4118549228d90cba0

+0

嘿,斯隆,所以這確實讓查詢變得更加困難。特別是,我試圖建立祖父母和孫子女(像https://www.elastic.co/guide/en/elasticsearch/guide/current/grandparents.html),但似乎'inner_hits'停止工作。 ..你有什麼想法,爲什麼可能會發生? – user5243421