【问题标题】:Elasticsearch, search for domains in urlsElasticsearch,在 url 中搜索域
【发布时间】:2026-01-02 04:00:01
【问题描述】:

我们索引可能包含指向其他文档的链接的 HTML 文档。我们正在使用 elasticsearch,大多数关键字搜索都非常顺利,这很棒。

现在,我们正在添加更复杂的搜索,类似于 Google site:link: 搜索:基本上我们想要检索指向特定 URL 甚至域的文档。 (如果文档 A 有指向 http://a.site.tld/path/ 的链接,则搜索 link:http://a.site.tld 应该会得到它。

我们现在正在尝试实现这一目标的最佳方法。 到目前为止,我们已经从文档中提取了链接,并在我们的文档中添加了一个links 字段。我们将links 设置为不被分析。然后我们可以搜索匹配确切的 url link:http://a.site.tld/path/ 但当然 link:http://a.site.tld 不会产生任何结果。

我们最初的想法是创建一个新字段linkedDomains,它的工作方式类似......但可能存在更好的解决方案?

【问题讨论】:

    标签: elasticsearch mapping


    【解决方案1】:

    你可以试试Path Hierarchy Tokenizer:

    如下定义映射:

    PUT /link-demo
    {
      "settings": {
        "analysis": {
          "analyzer": {
            "path-analyzer": {
              "type": "custom",
              "tokenizer": "path_hierarchy"
            }
          }
        }
      },
      "mappings": {
        "doc": {      
          "properties": {
            "link": {
              "type": "string",
              "index_analyzer": "path-analyzer"          
            }
          }
        }
      }
    }
    

    索引文档:

    POST /link-demo/doc
    {
        link: "http://a.site.tld/path/"
    }
    

    以下术语查询返回索引文档:

    POST /link-demo/_search?pretty
    {
        "query": {
            "term": {
               "link": {
                  "value": "http://a.site.tld"
               }
            }
        }
    }
    

    要了解它是如何被编入索引的:

    GET link-demo/_analyze?analyzer=path-analyzer&text="http://a.site.tld/path"&pretty
    

    显示以下内容:

    {
      "tokens" : [ {
        "token" : "\"http:",
        "start_offset" : 0,
        "end_offset" : 6,
        "type" : "word",
        "position" : 1
      }, {
        "token" : "\"http:/",
        "start_offset" : 0,
        "end_offset" : 7,
        "type" : "word",
        "position" : 1
      }, {
        "token" : "\"http://a.site.tld",
        "start_offset" : 0,
        "end_offset" : 18,
        "type" : "word",
        "position" : 1
      }, {
        "token" : "\"http://a.site.tld/path\"",
        "start_offset" : 0,
        "end_offset" : 24,
        "type" : "word",
        "position" : 1
      } ]
    }
    

    【讨论】: