lucene修改索引——(六)

原理:

  修改的原理是先删除,后增加一个,这也是常用的一种修改的方式。

  删除的文档的id不会被新增加的文档占用,类似于mysql的自增,当删除一个id=2时,以后id=2就是空着的,不会上来一个把2给占用。再添加是往后面增加。

 

代码:

  删除fileName 为 javaweb的索引,然后新增加一个索引,索引的term是fileN与fileC,值分别是"测试文件名"与"测试文件内容"。

原来的索引结构:

 

 

执行代码:

//
    public IndexWriter getIndexWriter() throws Exception{
        // 第一步:创建一个java工程,并导入jar包。
        // 第二步:创建一个indexwriter对象。
        Directory directory = FSDirectory.open(new File("E:\\lucene&solr\\index"));
        // Directory directory = new RAMDirectory();//保存索引到内存中 (内存索引库)
        Analyzer analyzer = new StandardAnalyzer();// 官方推荐
        IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, analyzer);
        return new IndexWriter(directory, config);
    }

 

//修改
    @Test
    public void testUpdate() throws Exception {
        IndexWriter indexWriter = getIndexWriter();
        Document doc = new Document();
        doc.add(new TextField("fileN", "测试文件名",Store.YES));
        doc.add(new TextField("fileC", "测试文件内容",Store.YES));
        indexWriter.updateDocument(new Term("fileName","javaweb"), doc, new IKAnalyzer());
        indexWriter.close();
    }

 

 

执行后的结构:

八个文档,原来有十个,删除三个增加一个变为8个。

 

 

查看文档结构:(删除后其文档ID仍然保留着,因此是是一个)

 

posted @ 2017-08-05 19:57  QiaoZhi  阅读(561)  评论(0编辑  收藏  举报