本文介绍如何使用ElasticsearchCRUD来定义Elasticsearch中类型的映射。 可以使用ElasticsearchCRUD的属性来定义Elasticsearch中的Core Types定义。
映射属性
可以使用ElasticsearchCRUD中的属性定义映射定义。 支持大部分Elasticsearch核心类型定义。 下面是一个使用Elasticsearch映射定义的类的例子。
public class AmazingThisMapping
{
public int Id { get; set; }
[ElasticsearchInteger(Coerce=true)]
public int NumberOf { get; set; }
[ElasticsearchString(CopyTo = "data")]
public string Name { get; set; }
public string Description { get; set; }
public string Data { get; set; }
[ElasticsearchInteger]
public short SmallAmount { get; set; }
[ElasticsearchString(Boost = 1.4, Fields = typeof(FieldDataDefNotAnalyzed), Index = StringIndex.analyzed)]
public string DescriptionBothAnayzedAndNotAnalyzed { get; set; }
[ElasticsearchDouble(Boost = 2.0,Store=true)]
public double Cost { get; set; }
[ElasticsearchDate]
public DateTime Timestamp { get; set; }
[ElasticsearchDate]
public DateTimeOffset TimestampWithOffset { get; set; }
}
一旦已经定义了具有映射的类,可以使用context.CreateIndex
方法在Elasticsearch中创建它。
using (var context = new ElasticsearchContext(ConnectionString, new ElasticsearchSerializerConfiguration(ElasticsearchMappingResolver)))
{
context.TraceProvider = new ConsoleTraceProvider();
context.CreateIndex<AmazingThisMapping>();
}
not_analyzed
,analyzed
字符串字段的示例
有时需要同时保存analyzed
和non-analyzed
的搜索请求的字符串。这是通过Elasticsearch中的字段属性实现的。 这可以在ElasticsearchCRUD中使用ElasticsearchString
属性中的Fields
属性定义。 此属性特性需要Type
。 然后,该类型定义所有必需属性为字段定义。
public class Whatever
{
[ElasticsearchString(Boost = 1.4, Fields = typeof(FieldDataDefNotAnalyzed), Index = StringIndex.analyzed)]
string DescriptionBothAnayzedAndNotAnalyzed { get; set; }
}
This class is used to define the field mappings in the fields property. This example has just one example, but you can define as many as required.
public class FieldDataDefNotAnalyzed
{
[ElasticsearchString(Index = StringIndex.not_analyzed)]
public string Raw { get; set; }
}
这将创建以下映射:
"descriptionbothanayzedandnotanalyzed": {
"type": "string",
"boost": 1.4,
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
}
copy_to定义
可以使用CopyTo属性或CopyToList属性定义copy_to字段映射。
public class Whatever
{
[ElasticsearchString(CopyTo = "data")]
public string Name { get; set; }
public string Description { get; set; }
public string Data { get; set; }
}
然后可以在搜索查询中使用。 以下查询搜索数据字段以匹配World
字符串。
{
"query": {
"bool": {
"must": [
{
"match" : {
"data" : "World" }
}
]
}
}
}
要查看可能的类型和映射定义的完整列表以及每个属性属性的含义,请参阅Elasticsearch中的Core Types文档。 这些在ElasticsearchCRUD.ContextAddDeleteUpdate.CoreTypeAttributes
命名空间中的ElasticsearchCRUD
中定义。 然后,这些映射定义可用于ElasticsearchCRUD中的任何类型的文档结构。