使用 ElasticSearch 跨多个文档进行匹配


Matching across Multiple documents with ElasticSearch

我对ElasticSearch相对较新。我将其用作pdf文档的搜索平台。我将PDF分解为文本页面,并将每个PDF作为elasticSearch记录输入,并带有相应的页面ID,父信息等。

我发现困难的是不仅将给定查询与 ES 中的单个文档匹配,而且使其匹配具有相同父 ID 的任何文档。因此,如果搜索两个术语,如果这些术语存在于实际 PDF 文档的第 1 页和第 7 页(ES 中的 2 个单独条目),我想匹配此结果。

从本质上讲,我的目标是能够搜索单个PDF的多个页面,匹配PDF中的任何文档页面上发生的匹配,并为搜索结果返回匹配的PDF文档列表,而不是匹配"页面"

您需要

在页面上使用"has_child"查询。我假设您已经定义了文档和页面的父/子关系的映射。然后,您可以编写一个"has_child"查询,在页面上搜索(子类型)但返回 PDF 文档(父类型):

{
  "query": {
    "has_child": {
      "type": "your_pages_type",
      "score_type": "max", // read document for more
      "query": {
        "query_string": {
          "query": "some text to search",
          "fields": [
            "your_pages_body"
          ],
          "default_operator": "and" // "and" if you want to search all words, "or" if you want to search any of words in query
        }
      }
    }
  }
}

这有点棘手。首先,您必须自己将查询拆分为术语。有一个术语列表(假设foobarbaz,您可以针对表示 PDF(父类型)的类型创建一个布尔查询,如下所示:

{
    "bool" : {
        "must" : [{
            "has_child" : {
                "type": "page",
                "query": {
                    "match": {
                        "page_body": "foo"
                    }
                }
            }
        }, {
            "has_child" : {
                "type": "page",
                "query": {
                    "match": {
                        "page_body": "bar"
                    }
                }
            }
        }, {
            "has_child" : {
                "type": "page",
                "query": {
                    "match": {
                        "page_body": "baz"
                    }
                }
            }
        }]
   }
}

此查询将查找每个术语至少包含一页的所有 PDF。