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

使用Nest Client在Elasticsearch中将嵌套属性复制到父对象

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

使用Nest Client在Elasticsearch中将嵌套属性复制到父对象

这是你怎么做

private static void Main(){    var defaultIndex = "my_index";    var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));    var settings = new ConnectionSettings(pool)        .DefaultIndex(defaultIndex);    var client = new ElasticClient(settings);    if (client.IndexExists(defaultIndex).Exists)        client.DeleteIndex(defaultIndex);    var createIndexResponse = client.CreateIndex(defaultIndex, c => c        .Settings(s => s .NumberOfShards(1) .NumberOfReplicas(0)        )        .Mappings(m => m .Map<Person>(mm => mm     .AutoMap()     .Properties(p => p         .Object<Address>(o => o  .Name(n => n.Address)  .AutoMap()  .Properties(pp => pp      .Text(t => t          .Name(nn => nn.Street)          .CopyTo(co => co   .Field(Infer.Field<Person>(ff => ff.Search))          )      )  )         )     ) )        )    );    var indexResponse = client.Index(new Person        { LastName = "foo", Address = new Address {     Street = "bar" }        } , i => i        .Refresh(Refresh.WaitFor)    );    var searchResponse = client.Search<Person>(s => s        .Query(q => q .Match(m => m     .Field(f => f.Search)     .Query("bar") )        )    );}public class Person{    public string Search { get; set; }    public string LastName { get; set; }    public Address Address { get; set; }}public class Address{    public string Street { get; set; }}

本质上

  1. 自动映射
    Person
    属性
  2. 显式将
    Address
    属性映射到
    Person
  3. 自动映射
    Address
    属性
  4. 明确映射该
    Street
    属性并进行设置
    CopyTo(...)
    。此时,泛型类型参数是
    Address
    类型,因此您需要使用
    Nest.Infer.Field<T>
    来访问的
    Search
    属性
    Person
    ,或使用字符串。

搜索返回期望的文档

{  "took" : 2,  "timed_out" : false,  "_shards" : {    "total" : 1,    "successful" : 1,    "skipped" : 0,    "failed" : 0  },  "hits" : {    "total" : 1,    "max_score" : 0.2876821,    "hits" : [      {        "_index" : "my_index",        "_type" : "person",        "_id" : "5tQDEWgBrKRHlz9qAve8",        "_score" : 0.2876821,        "_source" : {          "lastName" : "foo",          "address" : { "street" : "bar"          }        }      }    ]  }}

copy_to
Elasticsearch中的字段不一定需要在C#POCO上作为属性公开,因为
_source
不会包含它们的值。但是,作为属性公开对于强类型字段访问可能很有用。



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

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

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