Lucene stringfield没有结果

时间:2016-01-07 10:38:26

标签: lucene

我对Lucene 5.3.1进行了junit测试,这让我很困惑。我正在尝试测试搜索字段"代码"。索引中的每个文档都设置了此字段,因此搜索应返回索引中的所有文档。但我没有结果。当我改变"代码"字段到Textfield,一切都OK。 这是测试:

public class LuceneTest {
  private static final String CODE_FIELD_NAME = "code";
  private static final String ID_FIELD_NAME = "id";
  private static final String CODE_VALUE = "Address"; //$NON-NLS-1$
  private static final String TAGS_FIELD_NAME = "tags"; //$NON-NLS-1$

  @Test
  public void testCode() {
    Directory directory = new RAMDirectory();
    Analyzer analyzer = new StandardAnalyzer();
    try {
      createDocuments(analyzer, directory);
      IndexReader reader = DirectoryReader.open(directory);
      IndexSearcher searcher = new IndexSearcher(reader);
      List<Document> result = null;
      // code
      result = search("code:" + CODE_VALUE, searcher,
          analyzer);
      Assert.assertEquals(6, result.size());
    } catch (Exception e) {
      e.printStackTrace();
      Assert.fail(e.getMessage());
    }
  }

  private static List<Document> search(String queryString,
      IndexSearcher searcher, Analyzer analyzer) throws ParseException,
      IOException {
    Query q = new QueryParser(TAGS_FIELD_NAME, analyzer).parse(queryString);
    TopDocs docs = searcher.search(q, 10);
    List<Document> res = new ArrayList<Document>();
    for (ScoreDoc d : docs.scoreDocs) {
      Document doc = searcher.doc(d.doc);
      res.add(doc);
    }
    return res;
  }

  /**
   * @param analyzer
   * @param directory
   * @throws CorruptIndexException
   * @throws LockObtainFailedException
   * @throws IOException
   */
  private static void createDocuments(Analyzer analyzer, Directory directory)
      throws CorruptIndexException, LockObtainFailedException, IOException {
    IndexWriterConfig conf = new IndexWriterConfig(analyzer);
    IndexWriter iwriter = new IndexWriter(directory, conf);
    createDocument(1L, "Unter den Linden", "1", "Berlin", iwriter);
    createDocument(2L, "Broadway", "32, 2/20", "New York", iwriter);
    createDocument(3L, "Main road", "16", "New Hampshire", iwriter);
    createDocument(5L, "Moselgasse", "15", "Wien", iwriter);
    iwriter.close();
  }

  private static Document createDocument(Long id, String houseNum,
      String street, String city, IndexWriter iwriter)
      throws CorruptIndexException, IOException {
    Document doc = new Document();
    doc.add(new TextField(TAGS_FIELD_NAME, houseNum, Store.NO));
    doc.add(new TextField(TAGS_FIELD_NAME, street, Store.NO));
    doc.add(new TextField(TAGS_FIELD_NAME, city, Store.NO));
    doc.add(new LongField(ID_FIELD_NAME, id, Store.YES));
    doc.add(new StringField(CODE_FIELD_NAME,
 CODE_VALUE, Store.NO));
    iwriter.addDocument(doc);
    return doc;
  }
}

1 个答案:

答案 0 :(得分:0)

请查看Solr Text field and String field - different search behaviour。这个问题的答案可能也是你问题的答案。简短:StrFields无法应用任何标记化或分析/过滤器,而TextFields可以。