elasticsearch NET.InMemoryConnection未对响应数据应用筛选器

tcomlyy6  于 2023-02-21  发布在  ElasticSearch
关注(0)|答案(1)|浏览(118)

我有一个来自Elasticsearch.net的弹性客户端,它从InMemoryConnection获取数据,并在搜索中添加查询过滤器,但结果没有过滤。它将响应体的整个数据作为结果返回。
我错过了什么,还是这就是InMemoryConnection的工作原理?
CurrenciesDTO.cs

internal class CurrenciesDTO
    {
        [Keyword(Name = "CCY")]
        public string CCY { get; set; }
    }

Program.cs

using ConsoleApp_Elastic;
using Elasticsearch.Net;
using Nest;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Text;
using System.Threading;

List<CurrenciesDTO> listCurrencies = new List<CurrenciesDTO> { new CurrenciesDTO() { CCY = "GEL" }, new CurrenciesDTO() { CCY = "INR" }, new CurrenciesDTO() { CCY = "JPY" }, new CurrenciesDTO() { CCY = "USD" } };

var response = new
{
    took = 1,
    timed_out = false,
    _shards = new
    {
        total = 1,
        successful = 1,
        skipped = 0,
        failed = 0
    },
    hits = new
    {
        total = new
        {
            value = 193,
            relation = "eq"
        },
        max_score = 1.0,
        hits = Enumerable.Range(0, listCurrencies.Count).Select(i => (object)new
        {
            _index = "test.my.currencies",
            _type = "_doc",
            _id = listCurrencies[i].CCY,
            _score = 1.0,
            _source = new
            {
                CCY = listCurrencies[i].CCY,
            }
        })

    }

};

string json = JsonConvert.SerializeObject(response);
var responseBody =  Encoding.UTF8.GetBytes(json);

ConnectionSettings connectionSettings = new ConnectionSettings(new InMemoryConnection(responseBody, 200));
connectionSettings.OnRequestCompleted(apiCallDetails =>
{
    if (apiCallDetails.RequestBodyInBytes != null)
    {// not reaching here
        Console.WriteLine(
            $"{apiCallDetails.HttpMethod} {apiCallDetails.Uri} " +
            $"{Encoding.UTF8.GetString(apiCallDetails.RequestBodyInBytes)}");
    }
});
var client = new ElasticClient(connectionSettings);

var filterItems = new List<Func<QueryContainerDescriptor<CurrenciesDTO>, QueryContainer>>();

filterItems.Add(p => p.Term(v => v.Field(f=>f.CCY).Value("USD")));
var result = await client.SearchAsync<CurrenciesDTO>(s => s
                            .Index("test.my.currencies")
                            .Query(q => q.Bool(x => x.Filter(filterItems))), CancellationToken.None);
                           // .Query(q => q.Term(p => p.CCY, "USD")));
//expected 1 record but 4 records are returned.    
foreach (var a in result.Documents.ToArray())
    {
        Console.WriteLine(a.CCY);
    }
    Console.ReadLine();
vlf7wbxs

vlf7wbxs1#

是的,这是设计好的。创建InMemoryConnection是为了简化单元测试,对验证实际查询没有多大帮助。
为了确保Elasticsearch按照您所期望的方式进行配置,并且发送到Elasticsearch的查询是有效的,我建议使用Testcontainers
简单测试如下所示:

  • 使用Testcontainers帮助启动Elasticsearch新Docker示例
  • 索引某些数据
  • 运行你的代码对Elasticsearch运行在容器内

相关问题