ES字符串排序问题

如果对一个text field进行排序,结果往往不准确,因为分词后是多个单词,再排序就不是我们想要的结果了
通常解决方案是,将一个text field建立两次索引,一个分词,用来进行搜索;一个不分词,用来进行排序

创建索引
在ES6中没有String类型了,如果是不能被检索需要定义为keyword

PUT /web5
{
  "mappings": {
    "article": {
      "properties": {
        "title": {
          "type": "text",
          
          "fields": {
            "raw": {
              "type": "keyword"
            }
          },
          "fielddata": true
        },
        "content": {
          "type": "text"
        },
        "post_date": {
          "type": "date"
        },
        "author_id": {
          "type": "long"
        }
      }
    }
  }
}

查询出来的数据

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 3,
    "max_score": 1,
    "hits": [
      {
        "_index": "web5",
        "_type": "article",
        "_id": "2",
        "_score": 1,
        "_source": {
          "title": "two article",
          "content": "this is my two article",
          "post_date": "2018-11-02",
          "author_id": 123
        }
      },
      {
        "_index": "web5",
        "_type": "article",
        "_id": "1",
        "_score": 1,
        "_source": {
          "title": "one article",
          "content": "this is my one article",
          "post_date": "2018-11-01",
          "author_id": 123
        }
      },
      {
        "_index": "web5",
        "_type": "article",
        "_id": "3",
        "_score": 1,
        "_source": {
          "title": "three article",
          "content": "this is my three article",
          "post_date": "2018-11-03",
          "author_id": 123
        }
      }
    ]
  }
}

正常查询请求

GET /web5/article/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "title": {
        "order": "desc"
      }
    }
  ]
}

排序字段
在这里插入图片描述

全文查询请求

GET /web5/article/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "title.raw": {
        "order": "desc"
      }
    }
  ]
}

排序字段
在这里插入图片描述

“fields”: {“raw”: {“type”: “keyword”}} ,#可以对一个字段提供多种索引模式,使用text类型做全文检索,也可使用keyword类型做聚合和排序
“fielddata” : false, #针对text字段加快排序和聚合(doc_values对text无效);此项官网建议不开启,非常消耗内存

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值