1.加入依赖
Elasticsearch.model
Elasticsearch.Net
2.实体类
namespace Elasticsearch.model
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
}
3.编写工具类
using Elasticsearch.model;
using Elasticsearch.Net;
using Nest;
namespace Elasticsearch.config
{
public class ElasticsearchHelper
{
private static ElasticClient? _client = null;
public static ElasticClient GetClient() {
if (_client == null) {
var nodes = new Uri[]
{
new Uri("http://xxx:9200")
};
var pool = new StaticConnectionPool(nodes);
var settings = new ConnectionSettings(pool);
_client = new ElasticClient(settings);
}
return _client;
}
public static object Search() {
var response = GetClient().Search<User>(s => s
.Index("myuserindex")
.From(0)
.Size(10)
.Query(q =>
q.Term(t => t.Name, "kimchy")
|| q.Match(mq => mq.Field(f => f.Name).Query("tom"))
)
);
return response.Documents.ToList();
}
public static object Insert() {
var user = new User
{
Id = 2,
Name = "tom",
Age = 12
};
var response = GetClient().Index(user, idx => idx.Index("myuserindex"));
return response;
}
}
}
4.测试
using Elasticsearch.config;
using Microsoft.AspNetCore.Mvc;
namespace Elasticsearch.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
[HttpGet(Name = "my")]
public object Get()
{
ElasticsearchHelper.Insert();
return ElasticsearchHelper.Search();
}
}
}