2011-11-15 223 views
27

好的,至今我還沒有弄清楚。希望有人能提供一些見解。如何用彈性搜索搜索嵌套對象

鑑於以下文檔,我將如何搜索視頻標題中包含「測試」視頻的所有文檔?我正在使用HTTP API。 (基本上,你怎麼搜索嵌套對象有彈性的搜索?我知道必須有文檔在那裏,但我還沒有真正找到任何。)

[{ 
    id:4635, 
    description:"This is a test description", 
    author:"John", 
    author_id:51421, 
    video: { 
     title:"This is a test title for a video", 
     description:"This is my video description", 
     url:"/url_of_video" 
    } 
}, 
{ 
    id:4636, 
    description:"This is a test description 2", 
    author:"John", 
    author_id:51421, 
    video: { 
     title:"This is an example title for a video", 
     description:"This is my video description2", 
     url:"/url_of_video2" 
    } 
}, 
{ 
    id:4637, 
    description:"This is a test description3", 
    author:"John", 
    author_id:51421, 
    video: { 
     title:"This is a test title for a video3", 
     description:"This is my video description3", 
     url:"/url_of_video3" 
    } 
}] 

回答

24

OK,RTFM!我終於找到了這些頁面(應該事先花費更多時間處理文檔),並且似乎我們設置了保留視頻的屬性:嵌套,然後使用嵌套查詢。

http://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html

http://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-filter.html

希望這可以幫助別人的道路。

+1

您不一定需要嵌套視頻。請參閱http://www.elasticsearch.org/blog/2010/02/12/yourdatayoursearch.html以及我的答案。 – dira

+0

這裏是更新後的鏈接:http://www.elasticsearch.org/blog/your-data-your-search/ – swatkins

+1

我發現這篇博文的確很有用:http://www.elasticsearch.org/blog/managing -relations-inside-elasticsearch/ – Quin

42

您不一定需要嵌套視頻;您可以將其映射爲普通字段。這意味着它將存儲

'video:title': "This is a test title for a video3", 
'video:description':"This is my video description3", 
'video:url':"/url_of_video3" 

而且您可以搜索video.title:'test'

就我所知,嵌套字段在有多個嵌套項目時很有用,而且您只想爲嵌套項目進行查詢。例如,具有該數據

[{ 
    id:4635, 
    description:"This is a test description", 
    author:"John", 
    author_id:51421, 
    video: [ 
     { 
     title:"This is a test title for a video", 
     description:"This is my video description", 
     url:"/url_of_video" 
     }, 
     { 
     title:"This is an example title for a video", 
     description:"This is my video description2", 
     url:"/url_of_video2" 
     } 
    ] 
}, 
{ 
    id:4637, 
    description:"This is a test description3", 
    author:"John", 
    author_id:51421, 
    video: [ 
     { 
     title:"This is a test title for a video3", 
     description:"This is my video description3", 
     url:"/url_of_video3" 
     } 
    ] 
}] 

如果您想尋找video.title: 'test' and video.description: 'description2'和視頻沒有嵌套的,它會給你一個假的結果(因爲test是在第二,第一視頻和description2,但在所有你有兩個視頻領域)。

在這種情況下,如果你嵌套地圖視頻,它會記住每個視頻作爲一個獨立的實體,將搜索符合這些條件的個別影片,所以對於video.title: 'test' and video.description: 'description2'它會返回任何結果,爲video.title: 'example' and video.description: 'description2'它會返回一個結果。

+6

此答案提供了嵌套和簡單存儲子數組或對象之間的重要區別。嵌套在索引中創建額外的文檔,並在@swatkins情況下使事情不必要地複雜化。 –

+0

帶字符串列表的字段怎麼樣?如何只檢索列表中的元素以及在該字段列表中至少有一個匹配的文檔? –