2011-11-15 224 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

带字符串列表的字段怎么样?如何只检索列表中的元素以及在该字段列表中至少有一个匹配的文档? –