RavenDB:使用空格搜索,表现得像String.Contains

时间:2016-10-17 10:59:31

标签: c# linq ravendb

TL; DR 如何在RavenDB中运行完全等效的.Where(x => x.Name.Contains(value))查询,即使value字符串包含空格(白字符)?

我们用LINQ查询RavenDB。我们想用String.Contains查询 - 就像约束一样。由于RavenDb会阻止.Where(x => x.Name.Contains(value))个查询,因此我们按照文档中的示例使用LinqExtensions.Search扩展方法: query = query.Search(t => t.Name, $"*{value}*", escapeQueryOptions: EscapeQueryOptions.AllowAllWildcards, options: SearchOptions.And);

不幸的是,当搜索字词包含空格字符时,这不会按预期工作,很可能是因为:https://github.com/ravendb/ravendb/blob/f3b5f3a186d07776bf38bf9effab4d7d75d5c647/Raven.Client.Lightweight/Document/AbstractDocumentQuery.cs#L1759

我们一直在尝试手动空间转移,到目前为止没有成功:

var value = RavenQuery.Escape(filter.NameContains).Replace(" ", @"\ ");
query = query.Search(t => t.Name, $"*{value}*", escapeQueryOptions: EscapeQueryOptions.AllowAllWildcards, options: SearchOptions.And);

1 个答案:

答案 0 :(得分:2)

您需要将字段的Index选项设置为Analyzed

public class YourObject_ByName : AbstractIndexCreationTask<YourObject>
{
    public YourObject_ByName()
    {
        Map = objs => objs .Select(x => new { x.Name });

        Indexes.Add(x => x.Name, FieldIndexing.Analyzed);
    }
}

然后您可以使用DocumentQuery

进行查询
session.Advanced.DocumentQuery<YourObject, YourObject_ByName>()
    .Where("(Name: *term*)")
    .ToList();