前言:本文主要演示了如何通过c#来操作elasticsearch,分两个方面来演示:
索引数据
搜索数据
Note: 注意我索引数据和搜索数据是两个不同的例子,没有前后依赖关系
准备工作:需要在visual studio 用NuGet 搜索 NEST,下载NEST 2.3即可
注意elasticsearch和 NEST的版本,版本差异可能会导致写法不同
一、 索引数据演示
下面的c#代码有如下要点:
1. 通过es服务器 localhost:9200来定义es client
2. 导入前通过定义字段类型的类,自动mapping
var mappingBlogPost = elastic.Map(s => s.AutoMap());
Resume 这个类要提前根据数据类型进行定义:
using System;
namespace BotEsNest
{
using Nest;
[ElasticsearchType(Name = "candidate", IdProperty = "Id")]
public class Resume
{
[String(Name = "id", Index = FieldIndexOption.NotAnalyzed)]
public Guid? Id { get; set; }
[String(Name = "name", Index = FieldIndexOption.Analyzed)]
public string Name { get; set; }
[String(Name = "age", Index = FieldIndexOption.NotAnalyzed)]
public long Age { get; set; }
[String(Name = "skills", Index = FieldIndexOption.Analyzed)]
public string Skills { get; set; }
}
}
3. 构造数据
4. 导入数据
using Nest;
using System;
using System.Linq;
namespace BotEsNest
{
public class ImportEs
{
public static string ElasticsearchMethod()
{
var node = new Uri("http://localhost:9200");
var indexName = "esbot";
var settings = new ConnectionSettings(node).DefaultIndex(indexName);
var elastic = new ElasticClient(settings);
var res = elastic.ClusterHealth(); //
Console.WriteLine(res.Status);
if (!elastic.IndexExists(indexName).Exists)
{
var createIndexResponse = elastic.CreateIndex(indexName);
var mappingBlogPost = elastic.Map<Resume>(s => s.AutoMap());
//Console.WriteLine("createIndexResponse=" + createIndexResponse.IsValid);
//Console.WriteLine("mappingBlogPost=" + mappingBlogPost.IsValid);
}
string[] nameArray = { "Cody", "Blake", "Dennis", "Evan ", "Harris", "Jason ", "Lambert ", "Louis ", "Milton ", "Cody" };
string[] skillArray = { "c#", "c++", "java", "python", "php", "Linux", "ruby", "matlab", "perl", "powershell" };
long[] ageRange = { 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 };
for (int i = 0; i < 10; i++)
{
var resume = new Resume
{
Id = Guid.NewGuid(),
Name = nameArray[i],
Age = ageRange[i],
Skills = "My skill is Azure and " + skillArray[i]
};
IIndexResponse bulkIndexReponse = elastic.Index(resume, p => p
.Type(typeof(Resume))
.Id(i)
.Refresh());
}
var searchResult = elastic.Search<Resume>(sr => sr.Query(q => q.MatchAll()));
//Console.WriteLine(searchResult.Hits.Count());
//Console.ReadLine();
var resumesCount = searchResult.Hits.Count().ToString();
return resumesCount;
}
}
}
搜索返回的信息都包含在searchResult中。索引esbot也已经创建。可以通过Kibana或者REST API进行查看
二、搜索数据演示
1. 此处的数据源是es官网的bank account,我已经提前手动导入
2. 搜索数据的关键在于用lambda表达式构造搜索内容,下段代码是为了动态定制参数所做
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
namespace BotEsNest.Ext
{
public class Extension
{
public static Dictionary<string, Expression<Func<Resume, object>>> ResumeDIctionary()
{
return new Dictionary<string, Expression<Func<Resume, object>>>
{
{ "age",p=>p.Age},
{ "name",p=>p.Name}
};
}
public static Dictionary<string, Expression<Func<Bank, object>>> BankDictionary()
{
return new Dictionary<string, Expression<Func<Bank, object>>>
{
{ "account_number",p=>p.account_number},
{ "age",p=>p.age},
{"balance",p=>p.balance},
};
}
}
}
3.定义搜索类型
using Nest;
namespace BotEsNest
{
[ElasticsearchType(Name = "account", IdProperty = "Id")]
public class Bank
{
public long account_number { get; set; }
public string address { get; set; }
public long age { get; set; }
public long balance { get; set; }
public string city { get; set; }
public string email { get; set; }
public string employer { get; set; }
public string firstname { get; set; }
public string gender { get; set; }
public string lastname { get; set; }
public string state { get; set; }
}
}
4. 搜索,我大概写了三种搜索方式,比如:返回存款在40000到40100的人,返回数据中带有Miltoon的人,返回数据中带有35的人,返回结构存在searchResponse中
using System;
using Nest;
using BotEsNest.Ext;
namespace BotEsNest
{
public class Elasticsearch
{
public static string indexName = "bank";
public static Uri node = new Uri("http://localhost:9200");
public static ConnectionSettings settings = new ConnectionSettings(node).DefaultIndex(indexName);
public static ElasticClient elastic = new ElasticClient(settings);
public static ISearchResponse<Bank> esSearchNumber()
{
string dictionaryKey = "balance";
var dictionary = Extension.BankDictionary();
var rangeField = dictionary[dictionaryKey];
var gt = 40000;
var lt = 40100;
var searchResponse = elastic.Search<Bank>(es => es
.Query(q => q
.Range(r => r
.Name("")
.Field(rangeField)
.GreaterThan(gt)
.LessThan(lt)
.Boost(2.0))));
return searchResponse;
}
public static ISearchResponse<Bank>esSearchString()
{
string quertStr = "Miltoon";
var searchResponse = elastic.Search<Bank>(es => es
.Query(q =>
q.QueryString(qs => qs.Query(quertStr))));
return searchResponse;
}
public static ISearchResponse<Bank>esSearchField()
{
string queryStr = "35";
string dictionaryKey = "age";
var dictionary = Extension.BankDictionary();
var rangeField = dictionary[dictionaryKey];
var searchResponse = elastic.Search<Bank>(es => es
.Query(q => q
.Match(m => m
.Field(rangeField)
.Query(queryStr))));
return searchResponse;
}
}
}