如何映射现有索引进行排序?

How to map on existing indices for sorting?

我正在寻找 Elasticsearch 中的排序。在插入索引之前,我执行以下

PUT product
{
  "mappings": {
    "properties": {
      "manufacturer": {
        "type": "keyword"
      }
    }
  }
}

之后我可以与制造商进行排序。但是现在我想按品牌排序。

GET product/_search
{
  "size": 5, 
  "query": {
    "match": {
      "manufacturer": "abc"
    }
  },
  "sort": [
    {
      "brand": {
        "order": "desc"
      }
    }
  ]
}

它给我以下错误:

"type" : "illegal_argument_exception",
        "reason" : "Text fields are not optimised for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [brand] in order to load field data by uninverting the inverted index. Note that this can use significant memory."

是否可以在现有索引上进行映射?

您可以使用以下命令检查当前索引映射:

GET product

如果您当前的索引映射如下所示,那么您可以使用 brand.keyword

{
  "mappings": {
    "properties": {
      "manufacturer": {
        "type": "keyword"
      },
      "brand": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      }
    }
  }
}

如果您当前的索引映射与上述相同,您可以使用以下查询对品牌字段进行排序:

GET product/_search
{
  "size": 5, 
  "query": {
    "match": {
      "manufacturer": "abc"
    }
  },
  "sort": [
    {
      "brand.keyword": {
        "order": "desc"
      }
    }
  ]
}

Is it possible to make a mapping on already existing indices ?

是的,您可以使用以下命令更新现有索引的映射,但如果您正在更新现有字段的映射,则需要重新索引数据。

PUT product/_mapping
{
  "properties": {
    "brand": {
      "type": "text",
      "fields": {
        "keyword": {
          "type": "keyword",
          "ignore_above": 256
        }
      }
    }
  }
}