Lucene索引删除、更新、恢复和加权操作

    xiaoxiao2021-04-17  33

    Author: 百知教育 gaozhy 注:演示代码所使用jar包版本为 lucene-xxx-5.2.0.jar


    删除索引 try { // 1. 指定索引文件 FSDirectory directory = FSDirectory.open(Paths.get("F:/lucene/index/example02")); // 2. 创建分词器 Analyzer analyzer = new StandardAnalyzer(); // 3. 创建索引写入器 IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(analyzer)); // 4. 删除索引 //indexWriter.deleteAll(); QueryParser parser = new QueryParser("content", new StandardAnalyzer()); Query query = parser.parse("胡鑫哲"); // 删除content域中含有关键字“胡鑫哲”的所有文档 indexWriter.deleteDocuments(query); indexWriter.close(); directory.close(); } catch (Exception e) { e.printStackTrace(); } 更新索引 try{ // 1. 指定索引文件 FSDirectory directory = FSDirectory.open(Paths .get("F:/lucene/index/example02")); // 2. 创建分词器 Analyzer analyzer = new StandardAnalyzer(); // 3. 创建索引写入器 IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(analyzer)); // 4. 更新索引 // 创建新文档 Document document = new Document(); document.add(new Field("id","111",StringField.TYPE_STORED)); // 用新文档替换掉符合条件的文档 indexWriter.updateDocument(new Term("id","1"),document); indexWriter.close(); directory.close(); }catch(Exception e){ e.printStackTrace(); }

    恢复索引

    删除索引后,在同一方法中可以使用 indexWriter.rollback()方法恢复。

    索引域加权(类似百度搜素中的竞价排名)

    为索引域添加权值(默认为1.0f),这样,在进行搜索时,lucene会对文档进行评分,让权值高的内容更容易被用户搜索出来,而且排在前面。 如: Field field = new Field(“content”, new StringReader(“百知 金牌讲师 gaozhy”),TextField.TYPE_NOT_STORED); field.setBoost(0.8f); //设置索引域权值,默认为1.0f document.add(field);

    转载请注明原文地址: https://ju.6miu.com/read-673387.html

    最新回复(0)