Lucene查询索引
索引创建
以新闻文档为例,每条新闻是一个document,新闻有news_id、news_title、news_source、news_url、news_abstract、news_keywords这6个域,添加两个news document到索引中,下面再贴一下创建索引的代码:
package ucas.ir.lucene;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.Analyzer;
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.*;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class CreateIndex {
    public static void main(String[] args) {
        // 第一步:创建分词器
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_43);
        // 第二步:创建indexWriter配置信息
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_43, analyzer);
        // 第三步:设置索引的打开方式
        indexWriterConfig.setOpenMode(OpenMode.CREATE);
        // 第四步:设置索引第路径
        Directory directory = null;
        // 第五步:创建indexWriter,用于索引第增删改.
        IndexWriter indexWriter = null;
        try {
            File indexpath = new File("/Users/yp/Documents/workspace/UCASIR/WebContent/index");
            if (indexpath.exists() != true) {
                indexpath.mkdirs();
            }
            directory = FSDirectory.open(indexpath);
            if (indexWriter.isLocked(directory)) {
                indexWriter.unlock(directory);
            }
            indexWriter = new IndexWriter(directory, indexWriterConfig);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Document doc1 = new Document();
        doc1.add(new IntField("news_id", 1, Store.YES));
        doc1.add(new TextField("news_title", "围棋界对阿法狗集体服软 柯洁能成为人脑救星吗", Store.YES));
        doc1.add(new TextField("news_source", "搜狐体育", Store.YES));
        doc1.add(new TextField("news_url", "http://sports.sohu.com/20160316/n440533081.shtml", Store.YES));
        doc1.add(new TextField("news_abstract",
                "2016年3月16日 - 阿法狗4比1大胜李世石,它的表现几乎征服了整个围棋界,世界冠军级棋手们纷纷表示自己不是阿法狗的对手", Store.YES));
        doc1.add(new TextField("news_keywords", "阿法狗,李世石,柯洁", Store.YES));
        Document doc2 = new Document();
        doc2.add(new IntField("news_id", 2, Store.YES));
        doc2.add(new TextField("news_title", "任志强违纪究竟违反了什么?内幕惊动党中央", Store.YES));
        doc2.add(new TextField("news_source", "西陆频道", Store.YES));
        doc2.add(new TextField("news_url", "http://www.xilu.com/20160302/1000010000932707.html", Store.YES));
        doc2.add(new TextField("news_abstract",
                "2016年3月2日 - 核心:任志强在公开场合发表坚持资产阶级自由化立场、反对四项基本原则、反对党的改革开放决策的言论,妄议中央大政方针,公开与中央唱反调,背离了党的根本宗...",
                Store.YES));
        doc2.add(new TextField("news_keywords", "任志强,微博,被关", Store.YES));
        try {
            indexWriter.addDocument(doc1);
            indexWriter.addDocument(doc2);
            indexWriter.commit();
            indexWriter.close();
            directory.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("index create success!");
    }
}
再luke中查看: 
检索索引
索引创建好以后,查询可分为以下几个步骤: 
1.设置查询索引的目录(这里就是上面创建索引的目录). 
2.创建indexSearcher. 
3.设置query的分词方式 
4.设置查询域(比如查询域为”news_title”,那么就到新闻标题域去比对) 
5.设置查询字符串,也就是要查询的关键词. 
6.返回结果是一个文档集合,放在TopDocs中,通过循环TopDocs数组输出查询结果.
package ucas.ir.lucene;
import java.io.File;
import java.io.IOException;
import javax.print.Doc;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class IndexSearch {
    public static void main(String[] args) {
        Directory directory = null;
        try {
            File indexpath = new File("/Users/yp/Documents/workspace/UCASIR/WebContent/index");
            if (indexpath.exists() != true) {
                indexpath.mkdirs();
            }
            //设置要查询的索引目录
            directory = FSDirectory.open(indexpath);
            //创建indexSearcher
            DirectoryReader dReader = DirectoryReader.open(directory);
            IndexSearcher searcher = new IndexSearcher(dReader);
            //设置分词方式
            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_43);
            //设置查询域
            QueryParser parser = new QueryParser(Version.LUCENE_43, "news_title", analyzer);
            // 查询字符串
            Query query = parser.parse("阿法狗");
            System.out.println("query:"+query.toString());
            // 返回前10条
            TopDocs topDocs = searcher.search(query, 10);
            if (topDocs != null) {
                System.out.println("符合条件第文档总数:" + topDocs.totalHits);
                for (int i = 0; i < topDocs.scoreDocs.length; i++) {
                    Document doc = searcher.doc(topDocs.scoreDocs[i].doc);
                    System.out.println("news_id= " + doc.get("news_id"));
                    System.out.println("news_title= " + doc.get("news_title"));
                    System.out.println("news_source=" + doc.get("news_source"));
                    System.out.println("news_url=" + doc.get("news_url"));
                    System.out.println("news_abstract=" + doc.get("news_abstract"));
                    System.out.println("news_keywords=" + doc.get("news_keywords"));
                }
            }
            directory.close();
            dReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
这个例子中设置的查询域为news_title,查询词为”阿法狗”,那么新闻标题中有”阿法狗”的就会被返回。 
结果:
query:news_title:阿 news_title:法 news_title:狗
符合条件第文档总数:1
news_id= 1
news_title= 围棋界对阿法狗集体服软 柯洁能成为人脑救星吗
news_source=搜狐体育
news_url=http://sports.sohu.com/20160316/n440533081.shtml
news_abstract=2016年3月16日 - 阿法狗4比1大胜李世石,它的表现几乎征服了整个围棋界,世界冠军级棋手们纷纷表示自己不是阿法狗的对手
news_keywords=阿法狗,李世石,柯洁
查询域设置为news_keywords,查询词设置为微博,检索结果:
query:news_keywords:微 news_keywords:博
符合条件第文档总数:1
news_id= 2
news_title= 任志强违纪究竟违反了什么?内幕惊动党中央
news_source=西陆频道
news_url=http://www.xilu.com/20160302/1000010000932707.html
news_abstract=2016年3月2日 - 核心:任志强在公开场合发表坚持资产阶级自由化立场、反对四项基本原则、反对党的改革开放决策的言论,妄议中央大政方针,公开与中央唱反调,背离了党的根本宗...
news_keywords=任志强,微博,被关
总结
Lucene有多种分词方式和查询方式,上面的例子索引创建和索引查询都用的标准分词,后面会继续学习。
Lucene查询索引的更多相关文章
- lucene查询索引库、分页、过滤、排序、高亮
		
2.查询索引库 插入测试数据 xx.xx. index. ArticleIndex @Test public void testCreateIndexBatch() throws Exception{ ...
 - lucene查询索引之QueryParser解析查询——(八)
		
0.语法介绍:
 - lucene查询索引之Query子类查询——(七)
		
0.文档名字:(根据名字索引查询文档)
 - 搜索引擎学习(三)Lucene查询索引
		
一.查询理论 创建查询:构建一个包含了文档域和语汇单元的文档查询对象.(例:fileName:lucene) 查询过程:根据查询对象的条件,在索引中找出相应的term,然后根据term找到对应的文档i ...
 - Lucene查询索引(分页)
		
分页查询只需传入每页显示记录数和当前页就可以实现分页查询功能 Lucene分页查询是对搜索返回的结果进行分页,而不是对搜索结果的总数量进行分页,因此我们搜索的时候都是返回前n条记录 package c ...
 - 第六步:Lucene查询索引(优化一)
		
package cn.harmel.lucene; import java.io.IOException; import java.nio.file.Paths; import org.apache. ...
 - 第六步:Lucene查询索引
		
package cn.harmel.lucene; import java.io.IOException; import java.nio.file.Paths; import org.apache. ...
 - Lucene实现索引和查询
		
0引言 随着万维网的发展和大数据时代的到来,每天都有大量的数字化信息在生产.存储.传递和转化,如何从大量的信息中以一定的方式找到满足自己需求的信息,使之有序化并加以利用成为一大难题.全文检索技术是现如 ...
 - 学习笔记CB011:lucene搜索引擎库、IKAnalyzer中文切词工具、检索服务、查询索引、导流、word2vec
		
影视剧字幕聊天语料库特点,把影视剧说话内容一句一句以回车换行罗列三千多万条中国话,相邻第二句很可能是第一句最好回答.一个问句有很多种回答,可以根据相关程度以及历史聊天记录所有回答排序,找到最优,是一个 ...
 
随机推荐
- 多线程编程、java图形用户界面编程、Java I / O系统
			
线程概述 进程:是一种 “自包容”的运行程序 线程是进程当中的一个概念,最小处理单位 THread类.Runnable接口.Object类 创建新执行线程有两种方法:1:一种方法是将类声明为Threa ...
 - js中的栈与堆的讲解/基本数据类型与引用类型的讲解
			
1.栈(stack)和堆(heap) stack为自动分配的内存空间,它由系统自动释放:而heap则是动态分配的内存,大小不定也不会自动释放. 2.基本类型和引用类型 基本类型:存放在栈内存中的简单数 ...
 - 浅析php过滤html字符串,防止SQL注入的方法
			
批量过滤post,get敏感数据 复制代码 代码如下: $_GET = stripslashes_array($_GET);$_POST = stripslashes_array($_POST); 数 ...
 - python制作一个简单的中奖系统
			
注释: 展示图下的代码,我是用pycharm写的,是python解释器中的一种,本课没不同解释器的要求,可根据自己喜欢的解释器编写. 步骤: 本期给大家带来的是,一个简单的中奖系统,首先打开自己电脑上 ...
 - SQL发音考(搜寻SQL-86标准)
			
据我观察,中国的开发者创造了一种独特的SQL发音:/'sɜːkl/,既好听,又好读,挺好的.但是今年我开始做数据库相关的工作,作为一个专业人士,决定对SQL发音进行一些考证. 直接说结论吧,很多人沿用 ...
 - WPF 自定义TreeView控件样式,仿QQ联系人列表
			
一.前言 TreeView控件在项目中使用比较频繁,普通的TreeView并不能满足我们的需求.因此我们需要滴对TreeView进行改造.下面的内容将介绍仿QQ联系人TreeView样式及TreeVi ...
 - [LeetCode] Find Mode in Binary Search Tree 找二分搜索数的众数
			
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred ...
 - python的字符串
			
首先,字符串是python内置的数据类型,其特点是用引号引起来,并且可以是使用单引号('字符串'),双引号("字符串"),三个引号('''字符串''' 和""& ...
 - 谈一谈泛型(Generic)
			
谈一谈泛型 首先,泛型是C#2出现的.这也是C#2一个重要的新特性.泛型的好处之一就是在编译时执行更多的检查. 泛型类型和类型参数  泛型的两种形式:泛型类型( 包括类.接口.委托和结构 没有泛型枚 ...
 - Go学习——go+channel实战(转)
			
转载:http://studygolang.com/articles/2423 背景 在最近开发的项目中,后端需要编写许多提供HTTP接口的API,另外技术选型相对宽松,因此选择Golang + Be ...