2016-03-18 66 views
2

我创建了一个Lucene 4.10.3索引。匹配lucene整个字段的确切值

我正在使用他的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); 

当我尝试在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(); 
    } 

我们得到的结果作为后续

ANDHRA

安德拉邦

当我搜索“ANDHRA”如何获得唯一的“ANDHRA”的结果, 不是“安得拉邦”,如何匹配Lucene的整个领域。通过采用StandardAnalyzer

在先进的感谢

回答

1

如果您想要匹配领域的确切的,未经修改的和未经确认的价值,你根本不应该分析它。只需使用StringField而不是TextField

如果您想要进行某些分析(即缩小等),但没有标记,则可以在Analyzer实现中使用KeywordTokenizer

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