Lucene 4.2 StringField

Jestem nowy w Lucene. Mam dwa dokumenty i chciałbym mieć dokładne dopasowanie do pola dokumentu o nazwie „słowo kluczowe” (pole może występować wielokrotnie w dokumencie).

Pierwszy dokument zawiera słowo kluczowe „Adnotacja jest fajna”. Drugi dokument zawiera słowo kluczowe „Annotation is cool too”. Jak mam zbudować zapytanie, aby znaleźć tylko pierwszy dokument, gdy szukam „Adnotacja jest fajna”?

Czytałem coś o „StringField” i nie jest on tokenizowany. Jeśli zmienię pole „keyword” z „TextField” na „StringField” w metodzie „addDoc”, nic nie zostanie znalezione.

Oto mój kod:

private IndexWriter writer;

public void lucene() throws IOException, ParseException {
    // Build the index
    StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_42);
    Directory index = new RAMDirectory();
    IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_42,
            analyzer);
    this.writer = new IndexWriter(index, config);

    // Add documents to the index
    addDoc("Spring", new String[] { "Java", "JSP",
            "Annotation is cool" });
    addDoc("Java", new String[] { "Oracle", "Annotation is cool too" });

    writer.close();

    // Search the index
    IndexReader reader = DirectoryReader.open(index);
    IndexSearcher searcher = new IndexSearcher(reader);

    BooleanQuery qry = new BooleanQuery();

    qry.add(new TermQuery(new Term("keyword", "\"Annotation is cool\"")), BooleanClause.Occur.MUST);

    System.out.println(qry.toString());

    Query q = new QueryParser(Version.LUCENE_42, "title", analyzer).parse(qry.toString());

    int hitsPerPage = 10;
    TopScoreDocCollector collector = TopScoreDocCollector.create(
            hitsPerPage, true);

    searcher.search(q, collector);

    ScoreDoc[] hits = collector.topDocs().scoreDocs;

    for (int i = 0; i < hits.length; ++i) {
        int docId = hits[i].doc;
        Document doc = searcher.doc(docId);
        System.out.println((i + 1) + ". \t" + doc.get("title"));
    }

    reader.close();
}

private void addDoc(String title, String[] keywords) throws IOException {
    // Create new document
    Document doc = new Document();

    // Add title
    doc.add(new TextField("title", title, Field.Store.YES));

    // Add keywords
    for (int i = 0; i < keywords.length; i++) {
        doc.add(new TextField("keyword", keywords[i], Field.Store.YES));
    }

    // Add document to index
    this.writer.addDocument(doc);
}

questionAnswers(1)

yourAnswerToTheQuestion