栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

ElasticSearch按字符串长度排序

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ElasticSearch按字符串长度排序

您可以使用基于脚本的排序进行排序。

作为一个玩具示例,我用一些文档建立了一个琐碎的索引:

PUT /test_indexPOST /test_index/doc/_bulk{"index":{"_id":1}}{"name":"Bob"}{"index":{"_id":2}}{"name":"Jeff"}{"index":{"_id":3}}{"name":"Darlene"}{"index":{"_id":4}}{"name":"Jose"}

然后,我可以订购这样的搜索结果:

POST /test_index/_search{   "query": {      "match_all": {}   },   "sort": {      "_script": {         "script": "doc['name'].value.length()",         "type": "number",         "order": "asc"      }   }}...{   "took": 2,   "timed_out": false,   "_shards": {      "total": 5,      "successful": 5,      "failed": 0   },   "hits": {      "total": 4,      "max_score": null,      "hits": [         { "_index": "test_index", "_type": "doc", "_id": "1", "_score": null, "_source": {    "name": "Bob" }, "sort": [    3 ]         },         { "_index": "test_index", "_type": "doc", "_id": "4", "_score": null, "_source": {    "name": "Jose" }, "sort": [    4 ]         },         { "_index": "test_index", "_type": "doc", "_id": "2", "_score": null, "_source": {    "name": "Jeff" }, "sort": [    4 ]         },         { "_index": "test_index", "_type": "doc", "_id": "3", "_score": null, "_source": {    "name": "Darlene" }, "sort": [    7 ]         }      ]   }}

要按长度过滤,我可以通过类似的方式使用脚本过滤器:

POST /test_index/_search{   "query": {      "filtered": {         "query": { "match_all": {}         },         "filter": { "script": {    "script": "doc['name'].value.length() > 3",    "params": {} }         }      }   },   "sort": {      "_script": {         "script": "doc['name'].value.length()",         "type": "number",         "order": "asc"      }   }}...{   "took": 3,   "timed_out": false,   "_shards": {      "total": 5,      "successful": 5,      "failed": 0   },   "hits": {      "total": 3,      "max_score": null,      "hits": [         { "_index": "test_index", "_type": "doc", "_id": "4", "_score": null, "_source": {    "name": "Jose" }, "sort": [    4 ]         },         { "_index": "test_index", "_type": "doc", "_id": "2", "_score": null, "_source": {    "name": "Jeff" }, "sort": [    4 ]         },         { "_index": "test_index", "_type": "doc", "_id": "3", "_score": null, "_source": {    "name": "Darlene" }, "sort": [    7 ]         }      ]   }}

这是我使用的代码:

http://sense.qbox.io/gist/22fef6dc5453eaaae3be5fb7609663cc77c43dab

PS: 如果任何姓氏包含空格,则可能要

"index":"not_analyzed"
在该字段上使用。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/379907.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号