码迷,mamicode.com
首页 > 编程语言 > 详细

lucene学习笔记二(基于数组的lucene检索,索引删除)

时间:2015-10-03 14:28:59      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

构建数组:

private String[] ids = {"1","2","3","4","5","6"};
	private String[] emails = {"aa@qq.com","2aa@qq.com","3aa@qq.com","4wew@qq.com","5asdf@qq.com","6adsf@qq.com	"};
	private String[] contents = {
			"welcome to visited the space",
			"hello,my name is scc",
			"the day is first",
			"tommorw",
			"hello world",
			"i like football"
			};
	private int [] attachs = {2,3,1,4,5,6};
	private String[] names = {"张三","李四","王五","jetty","mick","divid"};

创建Directory:

private Directory directory;
	public IndexUtil(){
		try {
			//创建Directory
			directory = FSDirectory.open(new File("D:/workspace/lucene/index02").toPath());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}



创建文档,文档添加域:
public void index(){
		IndexWriter indexWriter = null;
		try {
			indexWriter = new IndexWriter(directory, new IndexWriterConfig(new StandardAnalyzer()));
			Document doc = null;
			for (int i = 0; i < ids.length; i++) {
				//创建文档(文档相当于数据库表中的每一条记录)
				doc = new Document();
				//为文档添加域(域相当于表中的每一个字段)
				doc.add(new TextField("id",ids[i],Field.Store.YES));
				doc.add(new TextField("email", emails[i],Field.Store.YES));
				TextField content = new TextField("content",contents[i],Field.Store.YES);
				content.tokenStream(new StandardAnalyzer(),null);
				doc.add(content);
				doc.add(new TextField("name", names[i],Field.Store.YES));
				//将文档写到索引中
				indexWriter.addDocument(doc);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(indexWriter!=null){
				try {
					indexWriter.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}



查询索引:
/**
	 * 查询索引
	 */
	public void query(){
		IndexReader indexReader = null;
		try {
			indexReader = DirectoryReader.open(directory);
			//通过reader可以获取文档的数量
			System.out.println("numDosc:"+indexReader.numDocs());
			System.out.println("maxDocs:"+indexReader.maxDoc());
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(indexReader!=null)
				try {
					indexReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		
	}



junit测试运行:

技术分享



索引的删除:

	/**
	 * 删除索引
	 */
	public void deleteIndex(){
		IndexWriter indexWriter = null;
		try {
			indexWriter = new IndexWriter(directory, new IndexWriterConfig(new StandardAnalyzer()));
			//参数是一个选项,可以是一个Query,也可以是一个Term,Term是一个精确查找的值
			indexWriter.deleteDocuments(new Term("id","1"));
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(indexWriter!=null)
				try {
					indexWriter.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}



junit测试:

当执行deleteIndex方法时,再执行查询索引

技术分享 





lucene学习笔记二(基于数组的lucene检索,索引删除)

标签:

原文地址:http://my.oschina.net/kkrgwbj/blog/513329

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!