2015-01-04 57 views
0

我正在索引一些项目,其中包括titlecost作为字段。成本是双重价值。 我准备的查询,如:带范围的Lucene查询

(title:item~0.8) AND (cost:[0.0 TO 200.0]) 

解析后,query.toString()看起来是这样的:

+title:item~0 +cost:[0.0 TO 200.0] 

从返回的结果,很明显,cost不考虑。 我知道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"); 
} 

回答

2

我结束了继承QueryParser然后创建一个NumericRange遇到cost时。它运作良好。

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])

1

QueryParser不会产生数字范围查询。所以你正在寻找价值在0.0到200.0之间的数值,而不是数字。此外,数字字段在索引中被转换为前缀编码形式,所以你的结果将是不可预测的。

最好通过查询API生成数字范围,使用NumericRangeQuery而不是QueryParser,然后用BooleanQuery将它们与解析后的查询结合起来。喜欢的东西:

Query parsedQuery = parser.parse(title:item~0.8); 
Query costQuery = NumericRangeQuery.newDoubleRange("cost", 0.00, 200.0, true, true); 
BooleanQuery finalQuery = new BooleanQuery(); 
finalQuery.add(new BooleanClause(parsedQuery, BooleanClause.Occur.MUST)); 
finalQuery.add(new BooleanClause(costQuery, BooleanClause.Occur.MUST)); 
+0

感谢您的解释。我还发现,这种方式并不适用。相反,我写了一个自定义的QueryParser,如果遇到“cost”列,它将创建新的NumericRange。我也会发布我的解决方案。 – isah 2015-01-05 13:03:22