我建立了一个 Lucene.net 书籍索引。一切正常,但我需要添加另一种查询索引的方法,但我不知道该怎么做。
基本上每本书都有一个适合的年龄段。这由两列表示,即 minAge 和 maxAge。两列都是整数。
我在下面的循环中索引和存储这些字段
foreach (var catalogueBook in books)
{
var book = new Book(catalogueBook.CatalogueBookNo,catalogueBook.IssueId);
var strTitle = book.FullTitle ?? "";
var strAuthor = book.Author ?? "";
// create a Lucene document for this book
var doc = new Document();
// add the ID as stored but not indexed field, not used to query on
doc.Add(
new Field(
"BookId",
book.CatalogueBookNo.ToString(System.Globalization.CultureInfo.InvariantCulture),
Field.Store.YES,
Field.Index.NOT_ANALYZED_NO_NORMS,
Field.TermVector.NO));
// add the title and author as stored and tokenized fields, the analyzer processes the content
doc.Add(
new Field("FullTitle",
strTitle.Trim().ToLower(),
Field.Store.YES,
Field.Index.ANALYZED,
Field.TermVector.NO));
doc.Add(
new Field("Author",
strAuthor.Trim().ToLower(),
Field.Store.YES,
Field.Index.ANALYZED,
Field.TermVector.NO));
doc.Add(
new Field("IssueId",
book.IssueId,
Field.Store.YES,
Field.Index.NOT_ANALYZED_NO_NORMS,
Field.TermVector.NO));
doc.Add(
new Field(
"PublicationId",
book.PublicationId.Trim().ToLower(),
Field.Store.YES,
Field.Index.NOT_ANALYZED_NO_NORMS,
Field.TermVector.NO));
doc.Add(
new Field(
"MinAge",
book.MinAge.ToString("0000"),
Field.Store.YES,
Field.Index.NOT_ANALYZED_NO_NORMS,
Field.TermVector.NO));
doc.Add(
new Field(
"MaxAge",
book.MaxAge.ToString("0000"),
Field.Store.YES,
Field.Index.NOT_ANALYZED_NO_NORMS,
Field.TermVector.NO));
doc.Add(new NumericField("Price",Field.Store.YES,true).SetDoubleValue(Convert.ToDouble(book.Price)));
//Now we can loop through categories
foreach(var bc in book.GetBookCategories())
{
doc.Add(
new Field("CategoryId",
bc.CategoryId.Trim().ToLower(),
Field.Store.YES,
Field.Index.NOT_ANALYZED_NO_NORMS,
Field.TermVector.NO));
}
// add the document to the index
indexWriter.AddDocument(doc);
}
// make lucene fast
indexWriter.Optimize();
}
如您所见,我正在填充 minAge 和 maxAge 字段,因为我认为对其运行 TermRangeQuery 是最简单的。
但是,我需要查询具有年龄的 minAge 和 maxAge 列,以查看该年龄是否在 minAge 和 maxAge 定义的年龄范围内。
SQL 会是
Select *
From books
where @age >= minAge and @age <= maxAge
不幸的是,我看不到这样做的方法。这在 Lucene.Net 中甚至可能吗?
最佳答案
如果没记错的话,您应该能够利用范围查询来做到这一点。这实际上是标准范围查询的反面,但您应该能够像这样:
+minAge:[* TO @age] +maxAge:[@age TO *]
或者,如果您构建查询对象,则具有上限或下限 null 的 RangeQuery(或更好的 NumericRangeQuery)用作开放式范围。
我以前使用过上面的语法,但支持似乎有点……不稳定。如果这不起作用,您始终可以设置一个足够低的下限 (0) 和一个足够高的上限(比如 1000),例如:
+minAge:[0000 TO @age] +maxAge:[@age TO 1000]
这应该足够安全,除非有玛士撒拉。
关于c# - Lucene.Net 大于/小于 TermRangeQuery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12648206/