lucene updateDocument not work



我正在使用Lucene 3.6。我想知道为什么更新不工作。有什么问题吗?

public class TokenTest
{
    private static String IndexPath = "D:\update\index";
    private static Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_33);
    public static void main(String[] args) throws Exception
    {
        try
        {
            update();
            display("content", "content");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    @SuppressWarnings("deprecation")
    public static void display(String keyField, String words) throws Exception
    {
        IndexSearcher searcher = new IndexSearcher(FSDirectory.open(new File(IndexPath)));
        Term term = new Term(keyField, words);
        Query query = new TermQuery(term);
        TopDocs results = searcher.search(query, 100);
        ScoreDoc[] hits = results.scoreDocs;
        for (ScoreDoc hit : hits)
        {
            Document doc = searcher.doc(hit.doc);
            System.out.println("doc_id = " + hit.doc);
            System.out.println("内容: " + doc.get("content"));
            System.out.println("路径:" + doc.get("path"));
        }
    }
    public static String update() throws Exception
    {
        IndexWriterConfig writeConfig = new IndexWriterConfig(Version.LUCENE_33, analyzer);
        IndexWriter writer = new IndexWriter(FSDirectory.open(new File(IndexPath)), writeConfig);
        Document document = new Document();
        Field field_name2 = new Field("path", "update_path", Field.Store.YES, Field.Index.ANALYZED);
        Field field_content2 = new Field("content", "content update", Field.Store.YES, Field.Index.ANALYZED);
        document.add(field_name2);
        document.add(field_content2);
        Term term = new Term("path", "qqqqq");
        writer.updateDocument(term, document);
        writer.optimize();
        writer.close();
        return "update_path";
    }
}

我假设您想更新文档,使字段"path" =" qqqq"。你完全颠倒过来了(请阅读文档)。

updateDocument执行两个步骤:

  1. 查找并删除包含term的所有文档
    • 在这种情况下,没有找到,因为您的索引文档不包含path:qqqq
  2. 新增document到索引

您似乎在做相反的事情,尝试按文档查找,然后将术语添加到其中,并且它不会这样工作。我想,您需要的是:

Term term = new Term("content", "update");
document.removeField("path");
document.add("path", "qqqq");
writer.updateDocument(term, document);

最新更新