java lucene 搜索_java – Lucene中的索引和搜索日期

本文介绍如何使用Lucene对已索引的日期字段执行范围查询,包括如何利用DateTools.dateToString()方法正确索引日期,并提供了一个完整的示例程序来展示如何在指定的时间范围内索引和搜索文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我尝试使用DateTools.dateToString()方法索引日期.它的工作正常索引和搜索.

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

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

任何解决这个?

提前致谢.

您需要在您的日期字段上使用TermRangeQuery.该字段始终需要使用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,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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值