需要在连接设置上打开EnableDebugMode,并在执行完查询之后,获取DebugInformation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Elasticsearch.Net;
using ElasticSearchHelper.Models;
using Nest;
using Newtonsoft.Json;
namespace ElasticSearchHelper.Helper
{
public class EsHelper
{
private readonly ElasticClient _elasticClient;
public EsHelper()
{
var connectorpool = new SingleNodeConnectionPool(new Uri("http://192.168.214.132:9200"));
var connect = new ConnectionSettings(connectorpool).BasicAuthentication("elastic","ellischen").EnableDebugMode().PrettyJson()
.RequestTimeout(TimeSpan.FromMinutes(2));
_elasticClient = new ElasticClient(connect);
}
public List<QueryModel> TestNestQuery()
{
SearchRequest searchrequest = new SearchRequest<QueryModel>("myindex")
{
Query = new NestedQuery()
{
Path = "aaa_meta",
Query = new TermQuery
{
Field = "aaa_meta.username",
Value ="chen"
},
IgnoreUnmapped = true
}
};
ISearchResponse<QueryModel> result = _elasticClient.Search<QueryModel>(searchrequest);
// 打印出来query dsl
var debugInformation = result.DebugInformation;
return result.Documents.ToList();
}
public bool create(string index)
{
if (_elasticClient.Indices.Exists(index) ==null)
_elasticClient.Indices.Create(index, c => c
.Map<QueryModel>(m => m.AutoMap()));
return true;
}
public string TestQuery()
{
SearchRequest searchrequest = new SearchRequest<QueryModel>("myindex")
{
Query = new TermQuery()
{
Field="test",
Value="test"
}
};
var result = _elasticClient.Search<QueryModel>(searchrequest);
return JsonConvert.SerializeObject(result);
}
}
}
- 创建model到es数据的映射
https://www.elastic.co/guide/en/elasticsearch/client/net-api/7.17/attribute-mapping.html
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElasticSearchHelper.Models
{
public class QueryModel
{
[Nested(Name ="aaa_meta")]
public List<AModel> AMeta { get; set; }
[Nested(Name = "bbb_meta")]
public BModel BMeta { get; set; }
[Text(Name = "test")]
public string Test { get; set; }
}
public class AModel
{
[Text(Name ="age")]
public string AgeNumber { get; set; }
[Text(Name = "username")]
public string User_Name { get; set; }
[Text(Name = "staffname")]
public string Staff_Name { get; set; }
}
public class BModel
{
[Text(Name = "a")]
public string AField { get; set; }
[Text(Name = "b")]
public string BField { get; set; }
[Text(Name = "c")]
public string CField { get; set; }
[Nested(Name = "d")]
public List<BChild> Children { get; set; }
}
public class BChild
{
[Text(Name ="h")]
public string TestField { get; set; }
}
}
执行第一步里面的create 创建index
3. 插入数据
POST myindex/_doc/1
{
"test":"test",
"aaa_meta":[{"username":"chen","staffname":"ellis","age":"100"}],
"bbb_meta":{"a":"haha","b":"bbb","c":"100","d":[{"h":"vv"}]}
}