Lucene - 在writer.updateDocuments()中使用LongPoint Field作为Term更新文档

时间:2017-06-30 19:42:14

标签: java lucene

我正在尝试使用writer.update(Term t,Document doc)方法更新索引中的文档。 如果我在Term中指定TextField,则更新成功,但是当我在Term中提供LongPoint时失败
我的代码示例:

package com.luceneserver.core;

import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.RAMDirectory;

public class SampleDocUpdates {

    public static void main(String[] args) throws IOException {
        IndexWriter writer = new IndexWriter(new RAMDirectory(), new IndexWriterConfig());
        IndexReader reader;
        IndexSearcher searcher;


        // first document in the index
        Document initialDoc = new Document();
        // adding a text field
        initialDoc.add(new TextField("foo_text", "abc", Store.YES));
        // adding a numeric field
        initialDoc.add(new LongPoint("foo_number", 1000));
        // adding stored field to display hits
        initialDoc.add(new StoredField("foo_number", 1000));


        writer.addDocument(initialDoc);


        // second document in index which should update the first one..
        Document newDoc = new Document();
        newDoc.add(new TextField("foo_text", "def", Store.YES));
        newDoc.add(new LongPoint("foo_number", 2000));
        newDoc.add(new StoredField("foo_number", 2000));


        // update doc with foo_text:abc with the newDoc instance.
        writer.updateDocument(new Term("foo_text", "abc"), newDoc);

        reader = DirectoryReader.open(writer);
        searcher = new IndexSearcher(reader);

        ScoreDoc[] scoreDocs = searcher.search(new MatchAllDocsQuery(), 1000).scoreDocs;

        for (ScoreDoc scoreDoc : scoreDocs) {
            System.out.println(searcher.doc(scoreDoc.doc).get("foo_text")+"\t"+searcher.doc(scoreDoc.doc).get("foo_number"));
            //'def  2000'
        }


    }

}

此代码使用第二个文档成功更新初始文档...
但如果我使用

  

writer.updateDocument(new Term(" foo_number",1000),newDoc);

失败......我的要求是通过基于LongPoint字段唯一识别文档来更新文档。
文档(lucene 6.3.0)只有updateDocuments(),条款作为选择标准,而不是LongPoint字段。
有没有其他方法可以实现这一目标?

1 个答案:

答案 0 :(得分:0)

updateDocument所做的就是删除包含该术语的文档,然后添加新文档。因此,您可以使用deleteDocuments来代替您传递查询,然后使用addDocument来完成同样的事情。

writer.deleteDocuments(LongPoint.newExactQuery("foo_number", 1000));
writer.addDocument(newDoc);