弹性搜索术语查询不匹配URL

时间:2016-05-19 14:22:19

标签: elasticsearch elasticsearch-net

我是弹性搜索的初学者,我上周正在研究POC。 我有一个URL字段作为我的文档的一部分,其中包含以下格式的URL:“http://www.example.com/foo/navestelre-04-cop”。

我无法定义到整个对象的映射,因为除了URL之外,每个对象都有不同的键。

以下是我创建索引的方法:

POST 
{
    "settings" : {
        "number_of_shards" : 5,
    "mappings" : {
            "properties" : {
                "url" : { "type" : "string","index":"not_analyzed" }
            }
    }
}
}

我保留我的URL字段为not_analyzed,因为我从某些资源中了解到,将字段标记为not_analyzed会阻止它进行标记化,因此我可以在术语查询中查找该字段的完全匹配。

我还尝试使用空白分析器作为URL值,因此没有任何空格字符。但是我再也无法获得成功的命中率。

以下是我的术语查询:

{
"query":{
    "constant_score": {
       "filter": {
       "term": {
          "url":"http://www.example.com/foo/navestelre-04-cop"
       }
       }
    }
}

}

我猜测问题出在分析器和标记器的某处,但我无法找到解决方案。任何形式的帮助都可以增强我的知识,并帮助我找到解决方案。 在此先感谢。

1 个答案:

答案 0 :(得分:2)

你有正确的想法,但看起来你的设置请求中的一些小错误会让你误入歧途。这是最终索引请求:

POST /test
{
    "settings": {
        "number_of_shards" : 5
    },                           
   "mappings": {
      "url_test": {
         "properties": {
            "url": {
               "type": "string",
               "index": "not_analyzed"
            }
         }
      }
   }
}

注意映射中添加的url_test类型。这让ES知道您的映射适用于此文档类型。此外,settingsmappings也是根对象的不同键,因此它们必须分开。由于您的初始设置请求格式不正确,因此ES忽略了它,并在您的文档上使用了标准分析器,这导致您无法使用查询进行查询。我指向the ES Mapping docs

我们可以索引两个文档进行测试:

POST /test/url_test/1
{
    "url":"http://www.example.com/foo/navestelre-04-cop"
}

POST /test/url_test/2
{
    "url":"http://stackoverflow.com/questions/37326126/elastic-search-term-query-not-matching-urls"
}

然后执行未经修改的搜索查询:

GET /test/_search
{
   "query": {
      "constant_score": {
         "filter": {
            "term": {
               "url": "http://www.example.com/foo/navestelre-04-cop"
            }
         }
      }
   }
}

产生这个结果:

"hits": [
         {
            "_index": "test",
            "_type": "url_test",
            "_id": "1",
            "_score": 1,
            "_source": {
               "url": "http://www.example.com/foo/navestelre-04-cop"
            }
         }
      ]
相关问题