Lucene小练四——为数字和日期添加索引

//主程序
package org.se.lucene;


import java.io.File;
import java.io.IOException;
//import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;

public class lucene_index {
		private String[] ids={"1","2","3","4","5","6"};
		private String[] emails={"welcometotyu","hellowboy",
				"higirl","howareyou","googluck","badgosh"};
		private String[] contents={"I like 1","I like 2","I like 3","I like 4" +
				"I like 5"};
		private int[] attachs={1,2,3,4,5,6};
		private String[] names={"liwu","zhangsan","xiaoqinag","laona",
				"dabao","lisi"};
		private Date[] dates=null;
		private Directory directory=null;
		private Map<String,Float> scores=new HashMap<String, Float>();
	
		
		public void index()
		{
			   IndexWriter writer=null;
			   Document doc=null;
			   try {
				writer =new IndexWriter(directory,new IndexWriterConfig(Version.LUCENE_36, 
						   new StandardAnalyzer(Version.LUCENE_36)));
				//writer.deleteAll();
				for(int i=0;i<ids.length;i++)
				{
					doc=new Document();
			    	doc.add(new Field("id",ids[i],Field.Store.YES,Field.Index.NOT_ANALYZED_NO_NORMS));
			    	doc.add(new Field("email",emails[i],Field.Store.YES,Field.Index.NOT_ANALYZED));
			    	doc.add(new Field("contents",contents[i],Field.Store.YES,Field.Index.ANALYZED));
			    	doc.add(new Field("name",names[i],Field.Store.YES,Field.Index.NOT_ANALYZED_NO_NORMS));
			    	//存储数字
			    	doc.add(new NumericField("attachs",Field.Store.YES,true).setIntValue(attachs[i]));
			    	//存储日期
			    	doc.add(new NumericField("date",Field.Store.YES,true).setLongValue(dates[i].getTime()));
			    	String et=emails[i].substring(emails[i].lastIndexOf("@")+1);
			    	System.out.println(et);
			    	if(scores.containsKey(et))
			    	{
			    		doc.setBoost(scores.get(et));
			    	}
			    	else {
			    		doc.setBoost(0.5f);
					}
			    	
			    	writer.addDocument(doc); 
				}
			} catch (CorruptIndexException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (LockObtainFailedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			   finally{
				   if(writer!=null)
				   {
					  try {
						writer.close();
					} catch (CorruptIndexException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}   
				   }
			   }
		}
        public void setDate()
        {
        	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-kk");
        	try {
        		dates=new Date[ids.length];
            	dates[0]=sdf.parse("2010-08-17");
            	dates[1]=sdf.parse("2011-02-17");
            	dates[2]=sdf.parse("2012-03-17");
            	dates[3]=sdf.parse("2011-04-17");
            	dates[4]=sdf.parse("2012-05-17");
            	dates[5]=sdf.parse("2011-07-17");
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
        } 
		public lucene_index()
		{
			setDate();
			try {
				directory=FSDirectory.open(new File("f:/lucene/index02"));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		public void quary()
		{
			try {
				IndexReader reader=IndexReader.open(directory);
				System.out.println("numdocs"+reader.numDocs());
				System.out.println("maxDocs"+reader.maxDoc());
				System.out.println("detelemaxDocs"+reader.numDeletedDocs());
				reader.close();
			} catch (CorruptIndexException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block 
				e.printStackTrace();
			}
			
		}
		
		@SuppressWarnings("deprecation")
		public void undelete()
		{
			try {
				//回复时必须把reader的只读设为false
				IndexReader reader=IndexReader.open(directory,false);
				reader.undeleteAll();
				reader.close();
			} catch (CorruptIndexException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	
		//清空回收站,强制优化
		public void forceDelete()
		{
			IndexWriter writer=null;
			try {
				writer=new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_36,
						new StandardAnalyzer(Version.LUCENE_36)));
				//参数十一个选项,可以是一个query,也可以是一个term  term就是一个精确查找的值
				//此时删除的文档并未完全删除,而是存储在回收站中,可以恢复的
				writer.forceMergeDeletes();
			} catch (CorruptIndexException e) {
				e.printStackTrace();
			} catch (LockObtainFailedException e) {
				e.printStackTrace();
			} catch (IOException e) {
			    e.printStackTrace();
			}
			finally{
				if (writer!=null) {
					try {
						writer.close();
					} catch (CorruptIndexException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		
		public void merge()
		{
			IndexWriter writer=null;
			try {
				writer=new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_36,
						new StandardAnalyzer(Version.LUCENE_36)));
				
				writer.forceMerge(2);
			} catch (CorruptIndexException e) {
				e.printStackTrace();
			} catch (LockObtainFailedException e) {
				e.printStackTrace();
			} catch (IOException e) {
			    e.printStackTrace();
			}
			finally{
				if (writer!=null) {
					try {
						writer.close();
					} catch (CorruptIndexException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		
		public void delete()
		{
			IndexWriter writer=null;
			try {
				writer=new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_36,
						new StandardAnalyzer(Version.LUCENE_36)));
				//参数十一个选项,可以是一个query,也可以是一个term  term就是一个精确查找的值
				//此时删除的文档并未完全删除,而是存储在回收站中,可以恢复的
				writer.deleteDocuments(new Term("id","1"));
			} catch (CorruptIndexException e) {
				e.printStackTrace();
			} catch (LockObtainFailedException e) {
				e.printStackTrace();
			} catch (IOException e) {
			    e.printStackTrace();
			}
			finally{
				if (writer!=null) {
					try {
						writer.close();
					} catch (CorruptIndexException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	
       //更新索引
	     public void update()
		{
			/*lucene本身不支持更新
			 * 
			 * 通过删除索引然后再建立索引来更新
			 * 
			 */
		       IndexWriter writer=null;
			   Document doc=null;
			   try {
				writer =new IndexWriter(directory,new IndexWriterConfig(Version.LUCENE_36, 
						   new StandardAnalyzer(Version.LUCENE_36)));
				writer.deleteAll();
				for(int i=0;i<ids.length;i++)
				{
					doc=new Document();
			    	doc.add(new Field("id",ids[i],Field.Store.YES,Field.Index.NOT_ANALYZED_NO_NORMS));
			    	doc.add(new Field("emails",emails[i],Field.Store.YES,Field.Index.NOT_ANALYZED));
			    	doc.add(new Field("contents",contents[i],Field.Store.YES,Field.Index.ANALYZED));
			    	doc.add(new Field("name",names[i],Field.Store.YES,Field.Index.NOT_ANALYZED_NO_NORMS));
			    	writer.updateDocument(new Term("id","1"), doc); 
				}
			} catch (CorruptIndexException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (LockObtainFailedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			   finally{
				   if(writer!=null)
				   {
					  try {
						writer.close();
					} catch (CorruptIndexException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}   
				   }
			   }	
		}

         public void serch()
         {
        	 try {
				IndexReader reader=IndexReader.open(directory);
				IndexSearcher searcher=new IndexSearcher(reader);
				TermQuery query=new TermQuery(new Term("contents","like"));
				TopDocs tds=searcher.search(query, 10);
				
				for(ScoreDoc sd:tds.scoreDocs)
				{
					Document doc=searcher.doc(sd.doc);
					System.out.println("("+sd.doc+"-"+doc.getBoost()+"-"+sd.score+")"+doc.get("name")+"["+doc.get("email")+"]-->"
							+doc.get("id")+","+doc.get("attachs")+","+doc.get("date"));
				}
			} catch (CorruptIndexException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch blocket
				e.printStackTrace();
			}
         }

}
//测试类
package org.se.lucene;

import org.junit.Test;

public class test {

	@Test
	public void testIndex()
	{
		lucene_index l_index=new lucene_index();
		l_index.index();
    }
	@Test
	
	public void testquary()
	{
		lucene_index l_index=new lucene_index();
		l_index.quary();
	}
	@Test
	public void testDelete()
	{
		lucene_index l_index=new lucene_index();
		l_index.delete();
	}
	@Test
	public void testunDelete()
	{
		lucene_index l_index=new lucene_index();
		l_index.undelete();
	}
	@Test
	public void testForceDelete()
	{
		lucene_index l_index=new lucene_index();
		l_index.forceDelete();
	}
	@Test
	public void testmerge()
	{
		lucene_index l_index=new lucene_index();
		l_index.merge();
	}
	
	@Test
	public void upDate()
	{
		lucene_index l_index=new lucene_index();
		l_index.update();
	}
	
	@Test
	public void testSercher()
	{
		lucene_index l_index=new lucene_index();
		l_index.serch();
	}
}


Navicat Premium 12 永久激活保姆级教程(附最新补丁下载) 本文详细介绍了Navicat Premium 12的高效使用方法,从安装配置到高级功能应用,帮助用户充分发挥这款数据库管理工具的全部潜力。内容包括数据库连接管理、数据查询与编辑、数据同步与结构对比等核心功能,以及性能优化最佳实践建议,提升数据库管理效率。 阅读详情

相关推荐

CTP接口入门

该文章主要讲什么 这篇文章的面向对象是有一些C++基础,并且想用C++来做程式化交易的同学。 这篇文章可以算是我的程式化学习笔记中的一篇。其中介绍了CTP的简单的使用方式,并且附上了一些代码以及我在试用的时候遇到的一些小坑。 什么是CTP CTP是上海期货推出的一套可供程序调用的交易接口。就好比官方给程序化交易提供了的一个专门的业务窗口。 接口相关文件下载 CTP接口可以在上期...

weizehua的专栏 4万+

Lucene五(添加日期数字类型索引

日期数字类型索引可以使用NumericField对象来添加,建立索引、搜索、测试的代码如下: public class IndexUtil { private String[] ids = {"1","2","3","4","5","6"}; private String[] emails = {"aa@itat.org","bb@itat.org","cc@cc.org","dd@s

刘永松的博客专栏 1648

cmake-3.10.3-win64-x64.msi

cmake-3.10.3-win64-x64.msi 安装包,2018年3月版本。

es文本分析java代码_Elasticsearch Lucene 数据写入原理 | ES 核心篇

前言最近 TL 分享了下 《Elasticsearch基础整理》,蹭着这个机会。写个小文巩固下,本文主要讲 ES -> Lucene的底层结构,然后详细描述新数据写入 ES Lucene 的流程原理。这是基础理论知识,整理了一下,希望能对 Elasticsearch 感兴趣的同学有所帮助。一、Elasticsearch & Lucene 是什么什么是 Elasticsearch...

weixin_28323057的博客 369

数据域 java_谈谈lucene的数据域存储

lucene的数据域也就是存储document文档的区域,只能通过ID号来定位文档,定位后可根据指定的字段获取所需数据。粗略的说fdt文件存储数据,fdx文件用于通过ID号来定位文档。(注:以下列出的内容只包含关键数据结构的原理部分,因为lucene在设计的时候考虑到各个版本的兼容性问题数据文件的完整性问题,而且也不是对源代码的完整解析,有兴趣的自己直接看源码吧)lucene在写入数据的时候是按...

weixin_35773740的博客 338

编程点滴.LUCENE.对数字日期、时间等进行索引

争取每日记录一些 索引数字 1.如果数字在文本中,比如"Be sure to include Form 1099 in your tax return".要搜索1099就要在创建索引使用不丢弃数字的分析器. 比如:WhitespaceAnalyzer或StandardAnalyzer 2.如果本身就是数字字段就可以使用NumericField进行索引,如果需要对这个字段进行排序,需要这个字段只能...

weixin_30699235的博客 288

13) 第二章 索引:用Lucene索引日期时间

      对Lucene而言,每个域都是String类型。然而在真实的应用中,我们还会遇到诸如日期、整数、浮点数等其它类型。如何是好?Lucene自然有其处理之道。     先让我们来看看Lucene是怎么处理日期类型的吧!     日期类型的使用场景可谓多之又多:邮件的寄出、收到日期;文件的创建日期、最后修改日期;HTTP响应中的最后修改日期等等。总之,绝大多数情况下,你会有处理日期的遭...

为中华之崛起而编码 399

lucene-索引日期索引数字排序

一、索引日期1、Field.Keyword(String,Date)方法DateField类进行索引索引今天的日期可以这么做:Document doc=new Document();doc.add(Field.Keyword("indexDate",new Date()));lucene内部使用了DateField类将日期转成字符串。2、可以先转换为YYYYMMDD格式的

深未来技术 1187

Lucene索引排序是使用了倒排序原理

Lucene 的索引排序是使用了倒排序原理 其实LUCENE写的真的挺烂的,不论算法还是代码都很一般,不知道国内为什么这么多人都用它,哎,中国程序员的技术水平真的差太远了,不过为了一些初级的程序员做研究之用,还是把这篇文章贴出来吧 Luce

卧薪尝胆的Blog 4673

lucene数字日期添加索引

热烈感谢我们亲爱的smallearth,我前期的程序在系统更新时被删掉了,现在发现smallearth写了,太好了,我可以转载了,就不用辛辛苦苦的重写了! //主程序 package org.se.lucene; import java.io.File; import java.io.IOException; //import java.sql.Date; import java.text.

KarlDoenitz的专栏 1108

Lucene笔记06-对日期数字进行索引

一、对数字进行索引 public void index() { IndexWriter indexWriter = null; int[] attachFiles = {1, 2, 3, 4, 5, 6}; try { indexWriter = new IndexWriter(directory, new IndexWriterConfig(Versi...

王劭阳的博客 559

lucene数字日期类型索引的创建

private int[] attachs = {1,4,6,2,3,8}; private Date[] dates = null; //日期的初始化 private void datesInit() {         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");         dates = new Date[6]; 

Kenan 494

Lucene——数字日期

为时间增加索引,增加的是NumericField域 //存储数字    doc.add(new NumericField("attach",Field.Store.YES,true).setIntValue(attachs[i]));   //存储日期    doc.add(new NumericField("date",Field.Store.YES,true).setLongValue

jingtianxiaozhi的专栏 850

Java开源在线考试系统怎么选?从技术选型到落地部署的完整指南

Java开源在线考试系统怎么选?本文从技术选型、核心功能、部署运维、二次开发等维度,梳理了Java开源在线考试系统的选型要点。

麦塔在线考试培训系统 339

大数据 之 Snappy

【代码】大数据 之 Snappy。

zhixingheyi_tian的博客 171

41面向对象(高级)-抽象类

当父类的某些方法,需要声明,但是又不确定如何实现时,可以将其声明为抽象方法,那么这个类就是抽象类。

weixin_52770734的博客 354

商超智能运营如何落地?从系统架构到实战避坑的完整技术路径

3. **多端交互展示层**:需覆盖顾客使用的**小程序、APP及H5公众号**,以及员工使用的管理后台。答:在应用层引入**适配器模式**。在项目启动时,应强制要求供应商或自研团队产出**部署文档**(含环境变量清单)**二次开发文档**(含核心流程时序图),确保后续维护不受限于个人。- **多租户插件**:MyBatis Plus的`TenantLineInnerInterceptor`可实现SQL层面的自动拼接`store_id`条件,防止开发者因SQL编写疏漏导致的数据越权。

weixin_56812938的博客 409

【手搓 Agent 第2.3关】搭建 Agent 进阶能力:工具注册中心架构重构

本篇优化了之前编写 Agent 时的杂乱硬编码,使用工具注册中心统一调度,促使后期增添工具更加容易。顺便优化了 RAG 知识库的懒加载,使 Agent 启动更快。

2502_92964924的博客 331

Java深入解析篇二十之JavaStream API详解

Stream(流)是引入的数据处理抽象,位于包。它表示从数据源产生的元素序列,并支持对其进行函数式、聚合式操作。不是集合:流不存储数据,只描述对数据的计算;不是 IO 流:与无关;惰性管道:中间操作只是登记,终端操作才触发实际计算。// 命令式写法(对照) // List<String> r = new ArrayList<>();

萧瑟余晖的博客 345
上一篇: Lucene小练三——索引删除,恢复,更新
下一篇: Lucene小练四——为数字和日期添加索引
S孙大宝
博客等级 码龄15年 55粉丝 65原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值