基于第一个字符的弹性搜索字母排序

问题描述 投票:3回答:5

我有一系列名字。

team dhoni
dhoni1
dibeesh 200
bb vineesh
devan

我想按字母顺序按升序排序(A - Z),如下面的顺序

bb vineesh
devan
dhoni1
dibeesh 200
team dhoni

制图

 "first_name": {
      "type": "string",
      "store": "true"
},

我试过了

{
  "sort": [
    {
      "first_name": {
        "order": "asc"

      }
    }
  ], 
 "query": {
    "match_all": {
    }
  }
}

当我运行此查询时,我按以下顺序获取名称。

dibeesh 200
bb vineesh
devan
team dhoni
dhoni1

弹性搜索以名字作为首选。

我怎么能阻止这个?

elasticsearch nosql
5个回答
6
投票

我认为问题是,你的字符串是在写入elasticsearch时分析的。它使用Standard Analyzer,使用带有标准令牌过滤器,小写令牌过滤器和停止令牌过滤器的标准令牌器构建标准类型的分析器。

这意味着什么,假设您正在使用字段“名称”,默认映射(标准分析器)。

当你索引时,

team dhoni, --> team, dhoni

dhoni1 --> dhoni1

dibeesh 200 --> dibeesh, 200

等等,

因此,通过排序显然dibeesh200将首先出现。 (因为它将按200而不是dibesh排序)

所以,如果你的字符串没有被分析(大写和小写的行为不同)或者你可以使用简单的分析器(这样你只能按字母排序,无论大写还是更低),或者你可以使用多字段来有分析和非分析版本。

这是一种方法,

POST x2/x3/_mapping
{
    "x3":{
        "properties": {
            "name" :{
                "type" :"string",
                "fields" :{
                    "raw" :{
                        "type": "string",
                        "index_analyzer": "simple"
                    }
                }
            }
        }
    }
}

这是查询,

POST x2/x3/_search
{
    "sort": [
       {
          "name.raw": {
             "order": "asc"
          }
       }
    ]
} 

这按预期工作。希望这可以帮助!!


4
投票

我有一个类似的问题,另一个答案并不适合我。我改为使用this documentation,并且能够通过这样的映射来解决

"name": { 
    "type":     "string",
    "analyzer": "english",
    "fields": {
        "raw": { 
            "type":  "string",
            "index": "not_analyzed"
        }
    }
}

然后像这样查询和排序

{
    "query": {
        "match": {
            "name": "dhoni"
        }
    },
    "sort": {
        "name.raw": {
            "order": "asc"
        }
    }
}

2
投票

我正在使用ElasticSearch 6.3(目前最新)

并且根据文档。,对于文本排序,您需要将类型设置为keyword

"title":{ 
    "type":     "text",
    "fields": {
        "raw": { 
            "type":  "keyword"
        }
    }
}

0
投票

keyword分析仪帮助我:

first_name: {
     type: "text",
     analyzer: "keyword"
}

Docs


0
投票

ASCII值的差异导致大写和小写开始的差异。因此,一个解决方案(技巧)只是保存您想要在其他字段名称中以小写形式排序的相同数据。并使用该字段进行排序。

这不是完美的方式,但在为下拉菜单排序数据时。这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.