匹配 lucene 整个字段的精确值

Ram*_*ure 3 lucene search phrase

我正在创建一个 Lucene 4.10.3 索引。

我正在使用他的 StandardAnalyzer。

    String indexpath="C:\\TEMP";
    IndexWriterConfig iwc=newIndexWriterConfig(Version.LUCENE_4_10_3,new StandardAnalyzer(CharArraySet.EMPTY_SET)); 
    Directory dir = FSDirectory.open(new File(indexpath));          
    IndexWriter indexWriter = new IndexWriter(dir, iwc);
    iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);   
    Document doc = new Document();
    doc.add(new TextField("city", "ANDHRA",Store.YES));
    doc.add(new TextField("city", "ANDHRA PRADESH",Store.YES));
    doc.add(new TextField("city", "ASSAM AND NAGALAND",Store.YES));
    doc.add(new TextField("city", "ASSAM",Store.YES));
    doc.add(new TextField("city", "PUNJAB",Store.YES));
    doc.add(new TextField("city", "PUNJAB AND HARYANA",Store.YES));
    indexWriter.addDocument(doc);
Run Code Online (Sandbox Code Playgroud)

当我尝试使用短语查询在 lucene 索引中搜索时

例如

 try {
        QueryBuilder build=new QueryBuilder(new KeywordAnalyzer());
        Query q1=build.createPhraseQuery("city","ANDHRA");      
        Directory dir = FSDirectory.open(new File("C:\\TEMP"));
        DirectoryReader indexReader = DirectoryReader.open(dir);    
        IndexSearcher searcher = new IndexSearcher(indexReader);
        ScoreDoc hits[] = searcher.search(q1,10).scoreDocs;
        Set<String> set=new HashSet<String>();
        set.add("city");
        for (int i=0; i < hits.length; i++) {
            Document document = indexReader.document(hits[i].doc,set);
            System.out.println(document.get("city"));
        }
     } catch (IOException e) {
        e.printStackTrace();
     }
Run Code Online (Sandbox Code Playgroud)

我们得到如下结果-

安得拉

安德拉邦

当我搜索“ANDHRA”时,如何仅获得“ANDHRA”结果,而不是“ANDHRA PRADESH”,如何使用 StandardAnalyzer 匹配 lucene 中的整个字段值?

fem*_*gon 5

如果您想匹配该字段的准确、未修改和未标记的值,则根本不应该对其进行分析。只需使用 aStringField而不是TextField

如果您想要一些分析(即小写或类似的),但没有标记化,您可以KeywordTokenizer在您的Analyzer实现中使用它。

如果您使用 aQueryParser创建查询,请注意解析器如何使用空格来分隔查询子句。您可能会觉得有必要写这样的查询: city:ANDHRA\ PRADESH(我相信QueryParser.escape会为你做这个)。