【问题标题】:Match lucene entire field exact value匹配lucene整个字段的精确值
【发布时间】:2016-03-18 06:28:46
【问题描述】:

我正在创建一个 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);

当我尝试使用短语查询在 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 PRADESH”,如何使用 StandardAnalyzer 匹配 lucene 中的整个字段值?

【问题讨论】:

    标签: search lucene phrase


    【解决方案1】:

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

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

    如果您使用QueryParser 创建查询,请注意解析器如何使用空格分隔查询子句。您可能会发现有必要编写如下查询:city:ANDHRA\ PRADESH(我确实相信QueryParser.escape 会为您这样做)。

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多