我正在为一些包含 title
和 cost
作为字段的项目建立索引。成本是双重值(value)。
我正在准备一个查询,例如:
(title:item~0.8) AND (cost:[0.0 TO 200.0])
解析后,query.toString()
看起来像这样:
+title:item~0 +cost:[0.0 TO 200.0]
从返回的结果来看,显然没有考虑成本
。
我确信 cost
已被索引,因为我可以检索它。
索引代码:
public void index(Set<Item> items) throws IOException {
String path = "D:\\lucenedata\\myproj";
Directory fsDir = FSDirectory.open(new File(path));
StandardAnalyzer analyzer = new StandardAnalyzer();
IndexWriterConfig iwConf = new IndexWriterConfig(Version.LUCENE_4_10_3, analyzer);
iwConf.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
IndexWriter indexWriter = new IndexWriter(fsDir, iwConf);
for (Item item : items) {
Document d = new Document();
if (item.getCost() != null) {
d.add(new DoubleField("cost", item.getCost().doubleValue(), Store.YES));
}
d.add(new TextField("title", item.getTitle(), Store.YES));
indexWriter.addDocument(d);
}
indexWriter.commit();
indexWriter.close();
System.out.println("Indexed " + items.size() + " items");
}
最佳答案
我最终对QueryParser
进行子类化,然后在遇到cost
时创建一个NumericRange
。效果很好。
public class WebSearchQueryParser extends QueryParser {
public WebSearchQueryParser(String f, Analyzer a) {
super(f, a);
}
protected Query getRangeQuery(final String field, final String min, final String max,
final boolean startInclusive, final boolean endInclusive) throws ParseException {
if ("cost".equals(field)) {
return NumericRangeQuery.newDoubleRange(field, Double.parseDouble(min), Double.parseDouble(max),
startInclusive, endInclusive);
}
return super.getRangeQuery(field, min, max, startInclusive, endInclusive);
}
}
然后初始化:
QueryParser queryParser = new WebSearchQueryParser("title", new StandardAnalyzer());
并像以前一样解析我的查询(title:item~0.8) AND (cost:[0.0 TO 200.0])
关于java - Lucene 查询范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27766198/