NEST 1.0.0 升级到 5.6.6 备忘
client 的创建方法没有更改;
创建索引的地方,原本是 Json 序列化后的字符串,升级后修改为实体了;
索引文档实体的字段上的特性需要修改,原本的
ElasticProperty
特性已经没有了;如果不指定特性,则 Elasticsearch 使用默认的字段类型(具体的参考 Auto mapping);
如果指定,写法可参考 Attribute mapping;
升级前代码
csharp
public class Message
{
/// <summary>
/// 虚拟的主键
/// </summary>
[ElasticProperty(Type = FieldType.String)]
public string Id { get; set; }
/// <summary>
/// 消息 Guid
/// </summary>
[ElasticProperty(Type = FieldType.String, Index = FieldIndexOption.NotAnalyzed)]
public string NewsGuid { get; set; }
}
csharp
var searchServer = ZConfig.GetConfigString("ElasticsearchServer");
var uris = searchServer.Split(",").Select(url => new Uri(url)).ToArray();
var connectionPool = new StaticConnectionPool(uris);
var settings = new ConnectionSettings(connectionPool);
var client = new ElasticClient(settings);
var indexResponse = client.Index(messageJsonDocument, o => o.Index(indexName).Type(indexType).Id(id).Parent(parent).Routing(routing));
升级后代码
csharp
[ElasticsearchType(Name = "message")]
public class Message
{
/// <summary>
/// 虚拟的主键
/// </summary>
[Keyword(Name = "Id")]
public string Id { get; set; }
/// <summary>
/// 消息 Guid
/// </summary>
[Keyword(Name = "NewsGuid")]
public string NewsGuid { get; set; }
}
csharp
var searchServer = ZConfig.GetConfigString("ElasticsearchServer");
var uris = searchServer.Split(",").Select(url => new Uri(url)).ToArray();
var connectionPool = new StaticConnectionPool(uris);
var settings = new ConnectionSettings(connectionPool);
var client = new ElasticClient(settings);
var indexResponse = client.Index(message, o => o.Index(indexName).Type(indexType).Id(id).Parent(parent).Routing(routing));
当索引如果不存在时,可以使用 Mappings
方法根据模型及其字段上的特性自动创建索引及定义字段属性,否则只会使用默认的 mapping 规则创建索引及定义字段属性。
csharp
if (!client.IndexExists(indexName).Exists)
{
var createIndexResponse = client.CreateIndex(indexName, c => c
.Mappings(ms => ms
.Map<T>(m => m.AutoMap())
)
);
}