多字段映射

883 发布于: 2021-04-19 读完约需 2 分钟

概述

为满足不同的需求,通常会以不同的方式在Elasticsearch中为相同的字段建立索引,例如将实体string属性映射为全文搜索的text类型,同时将其映射为用于结构化搜索、排序和聚合的keyword数据类型。或者,为了满足不同的全文搜索需求,可能将实体的string类型的属性映射成使用不同的分词器等等。

以下是一个简单的示例:

public class Person
{
    public string Name { get; set; }
}

当使用AutoMap()进行自动映射时,对于string类型的实体属性会被推断为text的Elasticsearch数据类型,并包含一个keyword的多字段子属性:

var createIndexResponse = _client.Indices.Create("myindex", c => c
    .Map<Person>(m => m
        .AutoMap()
    )
);

得到的JSON映射结果为:

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

这种映射会很有用,因为该属性既可以用于全文搜索,也可以用于结构化搜索、排序和聚合,如:

var searchResponse = _client.Search<Person>(s => s
    .Query(q => q
        .Match(m => m
            .Field(f => f.Name)
            .Query("Russ")
        )
    )
    .Sort(ss => ss
        .Descending(f => f.Name.Suffix("keyword")) 
    )
    .Aggregations(a => a
        .Terms("peoples_names", t => t
            .Field(f => f.Name.Suffix("keyword"))
        )
    )
);

生成的请求JSON为:

{
  "query": {
    "match": {
      "name": {
        "query": "Russ"
      }
    }
  },
  "sort": [
    {
      "name.keyword": {
        "order": "desc"
      }
    }
  ],
  "aggs": {
    "peoples_names": {
      "terms": {
        "field": "name.keyword"
      }
    }
  }
}

创建多字段映射

多字段映射可以使用.Fields()方法来手动创建,如下:

var createIndexResponse = _client.Indices.Create("myindex", c => c
    .Map<Person>(m => m
        .Properties(p => p
            .Text(t => t
                .Name(n => n.Name)
                .Fields(ff => ff
                    .Text(tt => tt
                        .Name("stop") 
                        .Analyzer("stop")
                    )
                    .Text(tt => tt
                        .Name("shingles")
                        .Analyzer("name_shingles") 
                    )
                    .Keyword(k => k
                        .Name("keyword") 
                        .IgnoreAbove(256)
                    )
                )
            )
        )
    )
);

得到的JSON映射结果为:

{
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "fields": {
          "stop": {
            "type": "text",
            "analyzer": "stop"
          },
          "shingles": {
            "type": "text",
            "analyzer": "name_shingles"
          },
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      }
    }
  }
}

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

发表评论

登录用户才能发表评论, 请 登 录 或者 注册