【发布时间】:2025-12-13 15:15:01
【问题描述】:
使用 Lucene 库,我需要对现有的搜索功能进行一些更改: 让我们假设以下对象:
名称:“端口对象 1”
数据:“TCP (1)/1000-2000”
查询(或搜索文本)是“1142” 是否可以在数据字段中搜索“1142”并找到端口对象 1,因为它指的是 1000-2000 之间的范围?
我只设法找到了数字范围查询,但这不适用于这种情况,因为我不知道范围...
package com.company;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
public class Main {
public static void main(String[] args) throws IOException, ParseException {
StandardAnalyzer analyzer = new StandardAnalyzer();
// 1. create the index
Directory index = new RAMDirectory();
IndexWriterConfig config = new IndexWriterConfig(analyzer);
IndexWriter w = new IndexWriter(index, config);
addDoc(w, "TCP (6)/1100-2000", "193398817");
addDoc(w, "TCP (6)/3000-4200", "55320055Z");
addDoc(w, "UDP (12)/50000-65000", "55063554A");
w.close();
// 2. query
String querystr = "1200";
Query q = new QueryParser("title", analyzer).parse(querystr);
// 3. search
int hitsPerPage = 10;
IndexReader reader = DirectoryReader.open(index);
IndexSearcher searcher = new IndexSearcher(reader);
TopDocs docs = searcher.search(q, hitsPerPage);
ScoreDoc[] hits = docs.scoreDocs;
// 4. display results
System.out.println("Found " + hits.length + " hits.");
for(int i=0;i<hits.length;++i) {
int docId = hits[i].doc;
Document d = searcher.doc(docId);
System.out.println((i + 1) + ". " + d.get("isbn") + "\t" + d.get("title"));
}
reader.close();
}
private static void addDoc(IndexWriter w, String title, String isbn) throws IOException {
Document doc = new Document();
doc.add(new TextField("title", title, Field.Store.YES));
doc.add(new StringField("isbn", isbn, Field.Store.YES));
w.addDocument(doc);
}
}
参考上面的代码。 查询“1200”应该找到第一个文档。
乐:
我认为我需要的与范围搜索完全相反: https://lucene.apache.org/core/5_5_0/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#Range_Searches
【问题讨论】:
标签: java search lucene lucene.net