有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用lucene索引查询国家代码?

我正在为citynames和countrycodes创建一个lucene索引(取决于彼此)。我希望国家代码是小写搜索和精确匹配

首先,我现在尝试查询单个countrycode并查找与该代码匹配的所有索引元素。我的结果总是空的

//prepare
VERSION = Version.LUCENE_4_9;
IndexWriterConfig config = new IndexWriterConfig(VERSION, new SimpleAnalyzer());

//index
Document doc = new Document();
doc.add(new StringField("countryCode", countryCode, Field.Store.YES));
writer.addDocument(doc);

//lookup
Query query = new QueryParser(VERSION, "countryCode", new SimpleAnalyzer()).parse(countryCode);

结果: 当我查询诸如“IT”、“DE”、“EN”等coutrycode时,结果总是空的。为什么? 对于两个字母的国家代码,SimpleAnalyzer是否来自


共 (2) 个答案

  1. # 1 楼答案

    我有点困惑。我假设您的索引编写器是在代码中未提供的某些部分中初始化的,但是您不是将Version传递到SimpleAnalyzer吗?SimpleAnalyzer没有参数构造函数,从3开始就没有。十、 无论如何

    这是我看到的唯一真正的问题。下面是一个使用您的代码的工作示例:

    private static Version VERSION;
    
    public static void main(String[] args) throws IOException, ParseException {
        //prepare
        VERSION = Version.LUCENE_4_9;
        Directory dir = new RAMDirectory();
        IndexWriterConfig config = new IndexWriterConfig(VERSION, new SimpleAnalyzer(VERSION));
        IndexWriter writer = new IndexWriter(dir, config);
    
        String countryCode = "DE";
    
        //index
        Document doc = new Document();
        doc.add(new TextField("countryCode", countryCode, Field.Store.YES));
        writer.addDocument(doc);
        writer.close();
    
        IndexSearcher search = new IndexSearcher(DirectoryReader.open(dir));
        //lookup
        Query query = new QueryParser(VERSION, "countryCode", new SimpleAnalyzer(VERSION)).parse(countryCode);
    
        TopDocs docs = search.search(query, 1);
        System.out.println(docs.totalHits);
    }
    
  2. # 2 楼答案

    对于StringField,可以使用TermQuery而不是QueryParser

    Directory dir = new RAMDirectory();
    IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_9, new SimpleAnalyzer(Version.LUCENE_4_9));
    IndexWriter writer = new IndexWriter(dir, config);
    
    String countryCode = "DE";
    
    // index
    Document doc = new Document();
    doc.add(new StringField("countryCode", countryCode, Store.YES));
    writer.addDocument(doc);
    writer.close();
    
    IndexSearcher search = new IndexSearcher(DirectoryReader.open(dir));
    //lookup
    Query query = new TermQuery(new Term("countryCode", countryCode));
    
    TopDocs docs = search.search(query, 1);
    System.out.println(docs.totalHits);