Elasticsearch 入門(三)使用Elasticsearch.Net & NEST作為elasticsearch客戶端 GitHub倉庫 https://github.com/elastic/elasticsearch-net 選擇 Elasticsearch.Net 作為客戶端 連接方式 ...
Elasticsearch 入門(三)使用Elasticsearch.Net & NEST作為elasticsearch客戶端
GitHub倉庫
- https://github.com/elastic/elasticsearch-net
- 選擇
Elasticsearch.Net
作為客戶端 - 連接方式
var node = new Uri("http://myserver:9200");
var config = new ConnectionConfiguration(node);
var client = new ElasticLowLevelClient(config);
var myJson = @"{ ""hello"" : ""world"" }";
client.Index<StringResponse>("myindex", "1", myJson);
var myJson = new { hello = "world" };
client.Index<BytesResponse>("myindex", "1", PostData.Serializable(myJson));
Elasticsearch.Net 封裝
- 新建
ElasticSearchClient
類
public class ElasticSearchClient
{
public ElasticLowLevelClient Client { get; }
private readonly IConfiguration _configuration;
public ElasticSearchClient(IConfiguration configuration)
{
_configuration = configuration;
Client = InitClient();
}
#region Methods
public async Task<string> Index(string index, string id, PostData body)
{
var response = await Client.IndexAsync<StringResponse>(index, id, body);
ResponseValidate(response);
return response.Body;
}
public async Task<List<string>> SearchWithHighLight(string index, string query)
{
var response = await Client.SearchAsync<StringResponse>(
index,
PostData.Serializable(new
{
from = 0,
size = 100,
query = new
{
match = new
{
content = query
}
},
highlight = new
{
pre_tags = new[] { "<tag1>", "<tag2>" },
post_tags = new[] { "/<tag1>", "/<tag2>" },
fields = new
{
content = new { }
}
}
}));
ResponseValidate(response);
var responseJson = (JObject)JsonConvert.DeserializeObject(response.Body);
var hits = responseJson["hits"]["hits"] as JArray;
var result = new List<string>();
foreach (var hit in hits)
{
var id = hit["_id"].ToObject<string>();
result.Add(id);
}
return result;
}
public async Task Delete(string index, string id)
{
var response = await Client.DeleteAsync<StringResponse>(index, id);
ResponseValidate(response);
}
#endregion
#region privates
private ElasticLowLevelClient InitClient()
{
var node = new Uri(_configuration.GetConnectionString("ElasticSearch"));
var settings = new ConnectionConfiguration(node);
var client = new ElasticLowLevelClient(settings);
return client;
}
private void ResponseValidate(StringResponse response)
{
if (response.Success == false)
{
throw new ResultException(response.Body);
}
}
#endregion
}
- 依賴註入 Startup.cs
services.AddScoped<ElasticSearchClient>();
- 使用
private readonly ElasticSearchClient _elasticSearchClient;
await _elasticSearchClient.Index(Article.EsIndex, article.ArticleUID,PostData.Serializable(article));