0

我设置了一个 Elasticsearch v5 索引,用于将配置哈希映射到 URL。

{
 "settings": {
   "analysis": {
    "analyzer": {
        "url-analyzer": {
           "type": "custom",
          "tokenizer": "url-tokenizer"
        }
    },
    "tokenizer": {
        "url-tokenizer": {
            "type": "path_hierarchy",
            "delimiter": "/"
        }
    }
}
},
"mappings": {
    "route": {
      "properties": {
        "uri": {
            "type": "string",
            "index": "analyzed",
            "analyzer": "url-analyzer"
        },
        "config": {
            "type": "object"
        }}}}}

我想将最长的路径前缀与最高分进行匹配,以便给定文档

{ "uri": "/trousers/", "config": { "foo": 1 }}
{ "uri": "/trousers/grey", "config": { "foo": 2 }}
{ "uri": "/trousers/grey/lengthy", "config": { "foo": 3 }}

当我搜索时/trousers,顶部结果应该是trousers,当我搜索/trousers/grey/short顶部结果时应该是/trousers/grey

相反,我发现最好的结果/trousers/trousers/grey/lengthy.

如何索引和查询我的文档以实现此目的?

4

1 回答 1

0

我有一个解决方案,喝了之后:如果我们将索引中的 URI 视为关键字,但仍然在搜索输入上使用 PathHierarchyTokenizer 怎么办?

现在我们存储以下文档:

/trousers /trousers/grey /trousers/grey/lengthy

当我们提交查询时/trousers/grey/short,search_analyzer 可以构建输入[trousers, trousers/grey, trousers/grey/short]

我们的前两个文档将匹配,我们可以使用自定义排序轻松选择最长的匹配。

现在我们的映射文档如下所示:

{
"settings": {
"analysis": {
    "analyzer": {
        "uri-analyzer": {
           "type": "custom",
          "tokenizer": "keyword"
        },
        "uri-query": {
                "type": "custom",
                "tokenizer": "uri-tokenizer"
        }
    },
    "tokenizer": {
        "uri-tokenizer": {
            "type": "path_hierarchy",
            "delimiter": "/"
        }
    }
}},

"mappings": {
    "route": {
      "properties": {
        "uri": {
            "type": "text",
            "fielddata": true,
            "analyzer": "uri-analyzer",
            "search_analyzer": "uri-query"
        },

        "config": {
            "type": "object"
        }
      }
    }
  }
}

```

我们的查询看起来像这样:

{
    "sort": {
            "_script": {
                    "script": "doc.uri.length",
                    "order": "asc",
                    "type": "number"
            }
    },
    "query": {
      "match": {
        "uri": {
                "query": "/trousers/grey/lengthy",
                "type": "boolean"
      }
    }
    }
}
于 2016-11-30T21:54:15.053 回答