Lucene的索引和搜索日期

use*_*024 10 java lucene

我试着用DateTools.dateToString()方法索引日期.它适用于索引和搜索.

但是我已经索引的数据有一些引用,它已经将Date作为新索引编入索引Date().getTime().

所以我的问题是如何RangeSearch Query对这些数据执行...

任何解决方案???

提前致谢.

Whi*_*g34 18

您需要TermRangeQuery在日期字段中使用a .该字段始终需要编入索引,DateTools.dateToString()以使其正常工作.以下是使用Lucene 3.0对日期范围进行索引和搜索的完整示例:

public class LuceneDateRange {
    public static void main(String[] args) throws Exception {
        // setup Lucene to use an in-memory index
        Directory directory = new RAMDirectory();
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
        MaxFieldLength mlf = MaxFieldLength.UNLIMITED;
        IndexWriter writer = new IndexWriter(directory, analyzer, true, mlf);

        // use the current time as the base of dates for this example
        long baseTime = System.currentTimeMillis();

        // index 10 documents with 1 second between dates
        for (int i = 0; i < 10; i++) {
            Document doc = new Document();
            String id = String.valueOf(i);
            String date = buildDate(baseTime + i * 1000);
            doc.add(new Field("id", id, Store.YES, Index.NOT_ANALYZED));
            doc.add(new Field("date", date, Store.YES, Index.NOT_ANALYZED));
            writer.addDocument(doc);
        }
        writer.close();

        // search for documents from 5 to 8 seconds after base, inclusive
        IndexSearcher searcher = new IndexSearcher(directory);
        String lowerDate = buildDate(baseTime + 5000);
        String upperDate = buildDate(baseTime + 8000);
        boolean includeLower = true;
        boolean includeUpper = true;
        TermRangeQuery query = new TermRangeQuery("date",
                lowerDate, upperDate, includeLower, includeUpper);

        // display search results
        TopDocs topDocs = searcher.search(query, 10);
        for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
            Document doc = searcher.doc(scoreDoc.doc);
            System.out.println(doc);
        }
    }

    public static String buildDate(long time) {
        return DateTools.dateToString(new Date(time), Resolution.SECOND);
    }
}
Run Code Online (Sandbox Code Playgroud)