我在一个 NHibernate 搜索索引中存储了多个实体,希望能够一次查询所有这些实体。该用例是一个返回混合结果的简单搜索页面。例如,代码可能如下所示:
public interface ISearchable {}
[Indexed(Index = "TheIndex")]
public class SearchableEntityA : ISearchable
{
// Some [Field]s
}
[Indexed(Index = "TheIndex")]
public class SearchableEntityB : ISearchable
{
// Some other [Field]s
}
这一切索引都很好,当然可以在原始 NHibernate 中查询,如下所示:
session.CreateCriteria<ISearchable>().List<ISearchable>();
我在 ISearchable 上有一些字段,但 NHibernate 映射中没有具体引用这些字段。
我的希望是我可以说:
var query = "some keyword";
fullTextSession.CreateFullTextQuery<ISearchable>(query).List<ISearchable>();
并检索 ISearchables 列表,其中包含来自各种不同实体的结果。然而,现实情况是它会抛出 NHibernate.HibernateException: Not amappedEntity: NetComposites.Model.ISearchable
。
那么,使用 NHibernate Search 实现类似多态查询的最简单方法是什么?
最佳答案
存在 CreateFullTextQuery
的重载,允许您指定要搜索的类型:
fullTextSession.CreateFullTextQuery(query, typeof(EntityA), typeof(EntityB)).List<ISearchable>();
必须指定所有类型有点笨拙,但它们加载得很好。我剩下的唯一问题是,我假设默认情况下可以进行所有字段搜索是不正确的,因此需要在所有可搜索实体的所有属性上构建 MultiFieldQueryParser
:
private static Query ParseQuery(string query, IFullTextSession searchSession)
{
var parser = new MultiFieldQueryParser(GetAllFieldNames(searchSession), new StandardAnalyzer());
return parser.Parse(query);
}
private static string[] GetAllFieldNames(IFullTextSession searchSession)
{
var reader =
searchSession.SearchFactory.ReaderProvider.OpenReader(
searchSession.SearchFactory.GetDirectoryProviders(typeof (Company)));
var fieldNames = reader.GetFieldNames(IndexReader.FieldOption.ALL);
return fieldNames.Cast<string>().ToArray();
}
关于.net - 使用 NHibernate Search 进行多态查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9176624/