如何在Elastic Search中将过滤器添加到更像此查询?

时间:2014-05-30 18:12:40

标签: elasticsearch

我想在弹性搜索中使用更像此查询来查找类似文档。但是我需要过滤执行查询的文档。

以下示例:我想找到类似于博客ID为123456但由作者120或作者123撰写的博客项目。

执行此查询时,我会收到所有作者的类似博客,因此不会过滤......

{
  "query":{
    "more_like_this" : {

        "fields" : ["body" ],  
        "docs" : [
              {
                "_id" : "123456"
              }
            ],
        "percent_terms_to_match" : 0.4,
            "min_term_freq" : 1
      }
  }
 },

"filter":{
  "and":[            
          {
            "type":{ "value":"blog" }
          },
          {
            "terms":{ "authorId": ["120", "123"] }
          }
        ]
}
}

2 个答案:

答案 0 :(得分:18)

尝试过滤查询,如下所示:

{
    "query": {
        "filtered": {
            "query": {
                "more_like_this": {
                    "fields": [
                        "body"
                    ],
                    "docs": [
                        {
                            "_id": "123456"
                        }
                    ],
                    "percent_terms_to_match": 0.4,
                    "min_term_freq": 1
                }
            },
            "filter": {
                "and": [
                    {
                        "type": {
                            "value": "blog"
                        }
                    },
                    {
                        "terms": {
                            "authorId": [
                                "120",
                                "123"
                            ]
                        }
                    }
                ]
            }
        }
    }
}

希望它有所帮助......!

答案 1 :(得分:4)

接受的答案是针对早期版本的ElasticSearch。这个在2.x +上运行得很好,也没有使用任何折旧的API

{
    "query": {
        "filtered": {
            "query": {
                "more_like_this": {
                    "fields": ["meta.keywords"],
                    "like": [{"_id": "5732759249d2b21f95641d50"}]
                }
            },
            "filter" : {
                "bool": {
                    "must": [                            
                        {"match": { "foo.bar": "A"}},
                        {"match": { "baz": "new"}}
                    ]
                }
            }
        }
    }
}