es存在某个字段的查阅_Elasticsearch:执行精确搜索,其中查询包含特殊字符,如'#'...

Get the results of only those documents which contain '#test' and ignore the documents that contain just 'test' in elasticsearch

解决方案

People may gripe at you about this question, so I'll note that it was in response to my comment on this post.

You're probably going to want to read up on analysis in Elasticsearch, as well as match queries versus term queries.

Anyway, the convention here is to use a .raw sub-field on a string field. That way, if you want to do searches involving analysis, you can use the base field, but if you want to search for exact (un-analyzed) values, you can use the sub-field.

So here is a simple mapping that accomplishes this:

PUT /test_index

{

"mappings": {

"doc": {

"properties": {

"post_text": {

"type": "string",

"fields": {

"raw": {

"type": "string",

"index": "not_analyzed"

}

}

}

}

}

}

}

Now if I add these two documents:

PUT /test_index/doc/1

{

"post_text": "#test"

}

PUT /test_index/doc/2

{

"post_text": "test"

}

A "match" query against the base field will return both:

POST /test_index/_search

{

"query": {

"match": {

"post_text": "#test"

}

}

}

...

{

"took": 2,

"timed_out": false,

"_shards": {

"total": 1,

"successful": 1,

"failed": 0

},

"hits": {

"total": 2,

"max_score": 0.5945348,

"hits": [

{

"_index": "test_index",

"_type": "doc",

"_id": "1",

"_score": 0.5945348,

"_source": {

"post_text": "#test"

}

},

{

"_index": "test_index",

"_type": "doc",

"_id": "2",

"_score": 0.5945348,

"_source": {

"post_text": "test"

}

}

]

}

}

But the "term" query below will only return the one:

POST /test_index/_search

{

"query": {

"term": {

"post_text.raw": "#test"

}

}

}

...

{

"took": 2,

"timed_out": false,

"_shards": {

"total": 1,

"successful": 1,

"failed": 0

},

"hits": {

"total": 1,

"max_score": 1,

"hits": [

{

"_index": "test_index",

"_type": "doc",

"_id": "1",

"_score": 1,

"_source": {

"post_text": "#test"

}

}

]

}

}

Here is the code I used to test it:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值