如何防止弹性搜索Nest客户端将poco名称作为slug注入URI中进行搜索



下面的代码将生成一个包含POCO名称的uri
https://demo.com/query/slug1/myIndexName/myPoco/_search
我只需要https://demo.com/query/slug1/myIndexName/_search

var node = new Uri("https://demo.com/query/slug1/");
var settings = new ConnectionSettings(node, defaultIndex: "myIndexName");
int skipCount = 0;
int takeSize = 100;
var client = new ElasticClient(settings);
do
{
    var searchResults = client.Search<myPoco>(x => x.Index("myIndexName")
        .Query(q => q
        .Bool(b => b
        .Must(m =>
            m.Match(mt1 => mt1.OnField(f1 => f1.status).Query("New")))))
        .Skip(skipCount)
        .Take(takeSize));
    foundStuff = (List<myPoco>)searchResults.Documents;
    foreach (foundThing item in searchResults.Documents)
    {
        //DO stuff
    }
    skipCount = skipCount + takeSize;
} while (foundStuff.Count == 100);

我是错过了一些简单的东西,还是这是AFU?

这不是AFU:)NEST将从传递给Search<T>()的泛型参数类型推断出要包含在URI中的类型名称。使用.AllTypes() 可以很容易地覆盖这一点

var searchResults = client.Search<myPoco>(x => x
    .Index("myIndexName")
    // specify all types
    .AllTypes()
    .Query(q => q
    .Bool(b => b
    .Must(m =>
        m.Match(mt1 => mt1.OnField(f1 => f1.status).Query("New")))))
    .Skip(skipCount)
    .Take(takeSize)
);

但请记住,这将在索引中的所有类型中进行搜索,并尝试将每个类型反序列化为myPoco类型。

作为对您评论的回应,indextype是两个不同的概念,因此如果您将类型命名为与索引相同的类型,则仍然会得到~/{index}/{type}/_search。使用NEST

您可以在连接设置上为具有.MapDefaultTypeIndices()的类型映射默认索引

var settings = new ConnectionSettings(new Uri("http://localhost:9200"))
    .MapDefaultTypeIndices(d => d.Add(typeof(myPoco), "myIndexName"));

类似地,您可以为类型映射默认类型名称

var settings = new ConnectionSettings(new Uri("http://localhost:9200"))
    .MapDefaultTypeNames(d => d.Add(typeof(myPoco), "myType"));

您可以滥用string.Empty映射为您的类型的默认类型名称,以获得您想要的的URI

最新更新