Elasticsearch - 加入两种不同类型的文档

时间:2016-05-08 12:45:37

标签: elasticsearch

我有这些文件:

mymovies

{
    "_index": "mymovies",
    "_type": "mymovie",
    "_id": "1",
    "_score": 1,
    "_source": {
     "title" : "Funny title is here"
     "genre" : "Comedy"
     "movieViews" : 901142
    }
}


 {
        "_index": "mymovies",
        "_type": "mymovie",
        "_id": "2",
        "_score": 1,
        "_source": {
         "title" : "Sad title is here"
         "genre" : "Drama"
         "movieViews" : 90
        }
 }

 {
        "_index": "mymovies",
        "_type": "mymovie",
        "_id": "3",
        "_score": 1,
        "_source": {
         "title" : "Sad Second title is here"
         "genre" : "Drama"
         "movieViews" : 9022
        }
 }

 {
        "_index": "mymovies",
        "_type": "mymovie",
        "_id": "4",
        "_score": 1,
        "_source": {
         "title" : "Horror title is here"
         "genre" : "Horror"
         "movieViews" : 9022
        }
 }

用户

{
  "Name" : "Doni de brun",
  "moviesLiked": [2,1,3]      
}
  1. 如何才能获得特定用户喜欢的类型?

  2. 是否有更好的方法来组织此查询的数据?

2 个答案:

答案 0 :(得分:4)

以下查询将完成工作:

POST movies/_search
{
  "size": 0

  , "query": {
    "terms": {
      "_id": [2,1,3]
    }
  }

  , "aggs": {
    "genres_for_user": {
      "terms": {
        "field": "genre",
        "size": 50
      }
    }
  }
}

您的文档结构看起来不错。

确保您拥有类型字段的not_analyzed索引。如果您为此字段保留默认分析器,请使用" Classic喜剧等#34;将被编入索引为两个关键字,并且在聚合查询中将为经典喜剧生成两个计数器。

答案 1 :(得分:1)

据我所知,没有简单的方法可以在Elasticsearch中加入查询。但您可以将数据嵌套为:

{
    "Name" : "Doni de brun",
    "moviesLiked": [
        {    
            "title" : "Horror title is here",
            "genre" : "Horror",
            "movieViews" : 9022 
        },
        {  
            "title" : "Sad title is here",
            "genre" : "Drama",
            "movieViews" : 90
        }
    ]      
}

缺点是您需要复制数据。但您可以使用嵌套查询轻松完成所需的搜索:

https://www.elastic.co/guide/en/elasticsearch/guide/current/nested-query.html