在.Net环境下使用elasticsearch实现大数据量的搜索
Posted dotNET跨平台
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在.Net环境下使用elasticsearch实现大数据量的搜索相关的知识,希望对你有一定的参考价值。
Elasticsearch是一个基于Apache Lucene(TM)的开源搜索引擎。无论在开源还是专有领域,Lucene可以被认为是迄今为止最先进、性能最好的、功能最全的搜索引擎库。
Elasticsearch使用标准的RESTful API和JSON。我们还用多种语言构建和维护客户机,如Java、Python、。NET、SQL和php。此外,我们的社区贡献了更多。它们易于使用,使用起来很自然,而且,就像Elasticsearch一样,不会限制您对它们的使用。
下面看下基于Net的使用
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));
创建
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<bool> Delete(string index, string id)
var response = await Client.DeleteAsync<StringResponse>(index, id);
ResponseValidate(response);
return response.Success;
#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
使用
private readonly ElasticSearchClient _elasticSearchClient;
await _elasticSearchClient.Index(Article.EsIndex, article.ArticleUID,PostData.Serializable(article));
以上是关于在.Net环境下使用elasticsearch实现大数据量的搜索的主要内容,如果未能解决你的问题,请参考以下文章
windows下fluentd传输日志到elasticsearch (fluentd elasticsearch https)
搭建Elasticsearch服务环境并实现将与mysql数据的同步
springboot+elasticsearch + rabbitMQ实现全文检索(项目搭建)
Elasticsearch学习-----第二章 windows环境下Elasticsearch同步mysql数据库
使用Logstash同步数据至Elasticsearch,Spring Boot中集成Elasticsearch实现搜索