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 索引的增删改查的更多相关文章

  1. elasticsearch索引的增删改查入门

    为了方便直观我们使用Head插件提供的接口进行演示,实际上内部调用的RESTful接口. RESTful接口URL的格式: http://localhost:9200/<index>/&l ...

  2. 列表(索引切片 增删改查 嵌套) range 元组的初识

    li = ["alex", "WuSir", "ritian", "barry", "wenzhou" ...

  3. lucene_03_索引的增删改查

    lucene索引的添加见 http://www.cnblogs.com/getchen/p/8615276.html 入门代码. 公共代码 public <T extends Query> ...

  4. Java solr 索引数据增删改查

    具体代码如下: import java.io.IOException; import java.util.*; import org.apache.solr.client.solrj.SolrClie ...

  5. elasticsearch java索引的增删改查

    1.创建索引并插入数据 Map<String, Object> json = new HashMap<String, Object>(); json.put("use ...

  6. Elasticsearch 索引文档的增删改查

    利用Elasticsearch-head可以在界面上(http://127.0.0.1:9100/)对索引进行增删改查 1.RESTful接口使用方法 为了方便直观我们使用Head插件提供的接口进行演 ...

  7. Es图形化软件使用之ElasticSearch-head、Kibana,Elasticsearch之-倒排索引操作、映射管理、文档增删改查

    今日内容概要 ElasticSearch之-ElasticSearch-head ElasticSearch之-安装Kibana Elasticsearch之-倒排索引 Elasticsearch之- ...

  8. 分布式搜索elasticsearch 索引文档的增删改查 入门

    1.RESTful接口使用方法 为了方便直观我们使用Head插件提供的接口进行演示,实际上内部调用的RESTful接口. RESTful接口URL的格式: http://localhost:9200/ ...

  9. mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)

    最后更新时间:2017-07-13 11:10:49 原始文章链接:http://www.lovebxm.com/2017/07/13/mongodb_primer/ MongoDB - 简介 官网: ...

随机推荐

  1. JAVA编程相关:eclipse如何导入已有工程

    eclipse使用过程中,经常会遇到导入外部eclispe工程的情况,导入外部eclipse也就是将已有的eclipse工程导入到eclipse中,那么如何导入外部工程呢?下面为大家分享导入已有ecl ...

  2. <?php echo "我的第一段 PHP 脚本!"; ?>

    <!DOCTYPE html><html><body> <?phpecho "我的第一段 PHP 脚本!";?> </body ...

  3. [ACM] n划分数m部分,它要求每一个部分,并采取了最大的产品(间隔DP)

    A - 爱管闲事 春希很爱管闲事,他每天都会抽出时间帮助一些同学,因为春希很死板,出于公平性,春希不会先帮助后来找他的同学. 如今有n个同学须要他的帮助,尽管他非常想一天之类帮助全部人,但毕竟精力有限 ...

  4. Windows Azure 安全最佳实践 - 第 5 部分:基于Claim 的标识,单点登录

    基于Claim的身份标识是处理网站与 Web 服务的身份认证和访问一种简单而强大的方式,无论您是在本地工作还是面向云工作.您可以通过减少自定义实施和使用基于Claim的单一简化标识模型,创建更安全的应 ...

  5. js实现密码强度验证

    <html> <head> <meta http-equiv="content-type" content="text/html" ...

  6. 用python将SQL格式文件改成自己想要的格式

    INSERT INTO TTT (NSAME, ID, AGE) VALUES ('AAA', '201023210816', '22'); 将上面的SQL格式改成以下的格式 AAA|20102321 ...

  7. 怎样使用 App Studio 高速定制你自己的 Universal Windows App

    今天之所以在写一篇关于 App Studio 的文章是由于,App Studio 经过了几次升级功能得到了明显提升还能够调用系统功能了.而且能够更方便的和应用商店关联公布 Universal Wind ...

  8. 高仿精仿快播应用android源码下载

    今天给大家在网上找到的一款高仿精仿快播应用android源码,分享给大家,希望大家功能喜欢. 说明源码更新中.... 源码即将上传 也可以到这个网站下载:download

  9. 类CL_ABAP_TYPEDESCR,动态取得运行时类型

    有时候我们要在程序运行的时候取得某个内表或者某个结构它的属性或者它的字段的属性,可能通过类CL_ABAP_TYPEDESCR和它的子类取得指定内表的属性.类CL_ABAP_TYPEDESCR和它的子类 ...

  10. JSP的学习(6)——九大隐式对象及其out对象

    本篇将介绍JSP中的九大隐式对象,并重点介绍其中的out对象. 我们在之前的博客<JSP的学习(1)——基础知识与底层原理>一文中已经知道,JSP最终要被翻译和转换成Servlet,在转换 ...