lucene4.4 索引的增删改查
package com.lucene.test;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.DocsAndPositionsEnum;
import org.apache.lucene.index.Fields;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Version;
publicclass IndexUtil {
privatestaticfinal Logger LOGGER = Logger.getLogger(IndexUtil.class);
private Directory directory = null;
private DirectoryReader reader = null;
private IndexWriterConfig config = null;
private IndexWriter writer = null;
publicstaticfinal IndexUtil Instance = new IndexUtil();
private IndexUtil() {
try {
directory = FSDirectory.open(new File("D:/lucene/index"));
config = new IndexWriterConfig(Version.LUCENE_44,
new StandardAnalyzer(Version.LUCENE_44));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*添加索引
*@throwsIOException
*/
publicvoid index() throws IOException {
writer = new IndexWriter(directory, config);
File file = new File("D:\\lucene\\example");
Document document = null;
int id = 0;
long start = new Date().getTime();
LOGGER.info("添加索引…………………………");
for (File f : file.listFiles()) {
document = new Document();
document.add(new StringField("name",f.getName(), Store.YES));
document.add(new IntField("id", id++,Store.YES));
document.add(new StringField("path",f.getAbsolutePath(), Store.YES));
document.add(new TextField("context", new FileReader(f)));
writer.addDocument(document);
}
long end = new Date().getTime();
LOGGER.info("添加索引完成,用时:" + (end - start) / 1000.0 + "s…………………………");
writer.close();
}
/**
*查询索引
*@throwsIOException
*@throwsParseException
*/
publicvoid search() throws IOException, ParseException {
reader = DirectoryReader.open(directory);
QueryParser parser = newQueryParser(Version.LUCENE_44, "context",
new StandardAnalyzer(Version.LUCENE_44));
Query query = parser.parse("lucene");
IndexSearcher searcher = new IndexSearcher(reader);
TopDocs docs = searcher.search(query,100);
/**
*reader.maxDoc()包含索引文档的总数包含可用的和已经删除的数量
*reader.numDocs()当前可用的索引文档的数量不包含已经删除的
*reader.numDeletedDocs()删除的索引文档的数量
*/
LOGGER.info("总记录:" + docs.totalHits + " 命中文档数:" + docs.scoreDocs.length
+ " 最大的文档数maxDoc:" + reader.maxDoc() + " 删除文件数numDeletedDocs:"
+ reader.numDeletedDocs() + " numDocs" + reader.numDocs());
for (ScoreDoc doc : docs.scoreDocs) {
Document document = reader.document(doc.doc);
LOGGER.info("id:" +document.get("id") + " name:"
+ document.get("name") + " path:" + document.get("path"));
}
reader.close();
}
/**
*更新索引
*@throwsIOException
*/
publicvoid update() throws IOException {
writer = new IndexWriter(directory, config);
Document document = new Document();
document.add(new StringField("name", "新文件", Store.YES));
document.add(new IntField("id", 12, Store.YES));
document.add(new StringField("path", "D:\\lucene\\example\\新文件.txt", Store.YES));
writer.updateDocument(new Term("id", "2"),document);
writer.commit();
writer.close();
}
/**
*删除索引删除的索引会保存到一个新的文件中(以del为结尾的文件相当于删除到回收站)
*@throwsIOException
*/
publicvoid delete() throws IOException {
writer = new IndexWriter(directory, config);
writer.deleteDocuments(new Term("name", "11.txt"));
writer.close();
}
/**
*删除所有的索引删除的索引会保存到一个新的文件中(以del为结尾的文件相当于删除到回收站)
*@throwsIOException
*/
publicvoid deleteAll() throws IOException {
writer = new IndexWriter(directory, config);
writer.deleteAll();
writer.close();
}
/**
*删除已经删除的索引对应上一个删除方法删除回收站的文件
*@throwsIOException
*/
publicvoid forceMergeDeletes() throws IOException {
writer = new IndexWriter(directory, config);
writer.forceMergeDeletes();// 清空回收站
writer.close();
}
/**
*显示所有的索引
*@throwsIOException
*/
publicvoid showIndex() throws IOException {
reader = DirectoryReader.open(directory);
Fields fields = MultiFields.getFields(reader); //获取directory中所有的field
for (String field : fields) {
LOGGER.info(field);
}
//显示 field 中 context的所有的分词
Terms terms = fields.terms("context");
TermsEnum termsEnum = terms.iterator(null);
BytesRef term = null;
while ((term=termsEnum.next()) !=null) {
System.out.print(term.utf8ToString()+"\t");//分词的内容
System.out.print(termsEnum.docFreq()+"\t");//出现该分词的有文档的数量
System.out.print(termsEnum.totalTermFreq()+"\t");//分词的总数
DocsAndPositionsEnumdocsAndPositionsEnum = termsEnum.docsAndPositions(null, null);
//如果要查询的字段没有被分词,docsAndPositionsEnum就会为空继续循环
if(docsAndPositionsEnum==null){
continue;
}
int docId ;
while ((docId = docsAndPositionsEnum.nextDoc())!= DocIdSetIterator.NO_MORE_DOCS) {
Document document = reader.document(docId);//获取document对象
System.out.print(docId+"\t");//分词的总数
System.out.print(document.get("name")+"\t");//可以获取document中field的值
int freq = docsAndPositionsEnum.freq();//该document中该分词出现的次数
for (int i = 0; i < freq; i++) {
System.out.print(docsAndPositionsEnum.nextPosition()+":"); //分词的位置
System.out.print("["+docsAndPositionsEnum.startOffset()+"");//分词起始偏移量的位置
System.out.print(docsAndPositionsEnum.endOffset()+"],");//分词结束偏移量的位置
System.out.print(docsAndPositionsEnum.getPayload()+"\t");
}
}
System.out.println();
}
reader.close();
}
}
lucene4.4 索引的增删改查的更多相关文章
- elasticsearch索引的增删改查入门
为了方便直观我们使用Head插件提供的接口进行演示,实际上内部调用的RESTful接口. RESTful接口URL的格式: http://localhost:9200/<index>/&l ...
- 列表(索引切片 增删改查 嵌套) range 元组的初识
li = ["alex", "WuSir", "ritian", "barry", "wenzhou" ...
- lucene_03_索引的增删改查
lucene索引的添加见 http://www.cnblogs.com/getchen/p/8615276.html 入门代码. 公共代码 public <T extends Query> ...
- Java solr 索引数据增删改查
具体代码如下: import java.io.IOException; import java.util.*; import org.apache.solr.client.solrj.SolrClie ...
- elasticsearch java索引的增删改查
1.创建索引并插入数据 Map<String, Object> json = new HashMap<String, Object>(); json.put("use ...
- Elasticsearch 索引文档的增删改查
利用Elasticsearch-head可以在界面上(http://127.0.0.1:9100/)对索引进行增删改查 1.RESTful接口使用方法 为了方便直观我们使用Head插件提供的接口进行演 ...
- Es图形化软件使用之ElasticSearch-head、Kibana,Elasticsearch之-倒排索引操作、映射管理、文档增删改查
今日内容概要 ElasticSearch之-ElasticSearch-head ElasticSearch之-安装Kibana Elasticsearch之-倒排索引 Elasticsearch之- ...
- 分布式搜索elasticsearch 索引文档的增删改查 入门
1.RESTful接口使用方法 为了方便直观我们使用Head插件提供的接口进行演示,实际上内部调用的RESTful接口. RESTful接口URL的格式: http://localhost:9200/ ...
- mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)
最后更新时间:2017-07-13 11:10:49 原始文章链接:http://www.lovebxm.com/2017/07/13/mongodb_primer/ MongoDB - 简介 官网: ...
随机推荐
- 8 cocos2dx加入场景切换效果,控制场景切换彻底完毕之后再运行动画
1 加入场景切换效果 供场景切换的类: CCTransitionJumpZoom CCTransitionProgressRadialCCW CCTransitionProgressRadial ...
- android 巧用资源文件(不断积累)
1.shape的使用 <shape xmlns:android="http://schemas.android.com/apk/res/android" > <s ...
- C#基础 大盘点
类型转换 tryParse 字符和整形转换 转译符: /' 单引号 /" 双引号 // 反斜杠 /0 空字符 /a 感叹号( ...
- oracle忘记密码,修改密码,解锁
忘记密码修改密码: alter user system identified by values abc111; 修改后的用户名system,密码abc111. 解锁: cmd->输入 :sql ...
- 网站遭遇DDOS简易处理
网站遭遇DDOS攻击 netstat -an | grep ESTABLISHED 我们看到有大量的链接存在着,并且都是ESTABLISHED状态 for i in `netstat -an | gr ...
- C++基础学习笔记----第四课(函数的重载、C和C++的相互调用)
本节主要讲了函数重载的主要概念以及使用方法,还有C和C++的相互调用的准则和具体的工程中的使用技巧. 函数重载 1.基本概念 函数重载就是用同一个函数名来定义不同的函数.使用不同的函数参数来搭配同一个 ...
- 一个问题:关于类型转换Type Cast(汇编讲解 as 语法)
问题如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 ...
- Eclipse TestNg插件
TestNg作为一个测试框架,也有eclipse的插件: 官网给的安装插件地址是 : For Eclipse 3.4 and above, enter http://beust.com/eclipse ...
- gulp工作流
小屁活动使用 gulp+less gulpfile.js var gulp = require('gulp'), cssmin = require('gulp-minify-css'), less = ...
- ORACLE 安装Oracle12遇到的问题
0.全然卸载Oracle10(Windows) 在Windows下多次安装Oracle会造成混乱.重装Oracle的话一定先要干净卸载曾经的Oracle. 一.有必要时先备份 二.卸载步骤 1.用DB ...