热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

lucen入门学习之一(初识Lucene)

Lucen最主要用到的又两个部分,一个是创建索引,一个是查询索引说明下下面的代码注意事项:1、如果自己比较懒的话,就把文档路径和索引路径创建到项目下,方便查看2、我下面的两个例子都是在D盘下创建Luc

Lucen最主要用到的又两个部分,一个是创建索引,一个是查询索引


说明下下面的代码注意事项:

1、如果自己比较懒的话,就把文档路径和索引路径创建到项目下,方便查看

2、我下面的两个例子都是在D盘下创建Lucene,然后分别在D:/Lucene下创建Index和Data两个文件夹

3、在Data中我创建了两个文件:record1.txt和record2.txt,内容分别为txt1和txt2,当然你也可以创建更多和更复杂的内容的文本

4、在搜索的时候我搜的是txt2所以能查到record2.txt。。-_-


一、创建索引

1、创建索引常用到的类有以下几个(有些事基类,其子类就不过多列举了,具体使用的时候再查)

IndexWriter

Direcory

Analyzer

Document

Field

具体意思就不多说了,如果你不清楚,点击这个链接http://pan.baidu.com/s/1pLrZzWB下载《lucene in action_中文版.pdf》,在第25页可以看到解释,

下面是关于创建索引的一个例子:

package com.burns.lucene_in_action;

import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.FieldSelectorResult;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexFileNameFilter;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import com.yiibai.lucene.TextFileFilter;

public class Indexer {


public static void main(String[] args) throws IOException {
//if (args.length != 2) {
//throw new IllegalArgumentException("Usage:java" + Index.class.getName() + " ");
//}
// String indexDir = args[0];
// String dataDir = args[1];
String indexDir = "D:\\Lucene\\Index";
String dataDir = "D:\\Lucene\\Data";

long start = System.currentTimeMillis();
Indexer indexer = new Indexer(indexDir);
int numIndexed;
try {
numIndexed = indexer.index(dataDir, new TextFileFilter());
} finally {
indexer.close();
}

long end = System.currentTimeMillis();
System.out.println("Indexing" + numIndexed + "files took" + (end - start) + "milliseconds");

}

public IndexWriter writer;

@SuppressWarnings("deprecation")
public Indexer(String indexDir) throws IOException {
Directory dir = FSDirectory.open(new File(indexDir));
writer = new IndexWriter(dir, new StandardAnalyzer(Version.LUCENE_30), true,
IndexWriter.MaxFieldLength.UNLIMITED);
}

public void close() throws CorruptIndexException, IOException {// 关闭Index
// Writer
writer.close();

}

public int index(String dataDir, FileFilter filter) throws IOException {
File[] files = new File(dataDir).listFiles();
for (File file : files) {
if (!file.isDirectory() && !file.isHidden() && file.exists() && file.canRead()
&& (filter == null || filter.accept(file))) {
indexFile(file);
}
}
return writer.numDocs();
}

private static class TextFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".txt");
}
}

protected Document getDocument(File f) throws IOException {
Document doc = new Document();
doc.add(new Field("contents", new FileReader(f)));
doc.add(new Field("filename", f.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("fullpath", f.getCanonicalPath(), Field.Store.YES, Field.Index.NOT_ANALYZED));
return doc;
}

private void indexFile(File f) throws IOException {
System.out.println("Indexing" + f.getCanonicalPath());
Document doc = getDocument(f);
writer.addDocument(doc);
}
}

執行結果如下:

IndexingD:\Lucene\Data\record1.txt
IndexingD:\Lucene\Data\record2.txt
Indexing2files took1954milliseconds
二、搜索/查询索引

常用的类如下:

IndexSearcher

Term

Query

TermQuery

TopDocs


例子代码如下:

package com.burns.lucene_in_action;

import java.io.File;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
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.Version;

public class Searcher {

public static void main(String[] args) throws Exception {
// if (args.length != 2) {
// throw new IllegalArgumentException("Usage: java" +
// Searcher.class.getName() + " ");
// }
//
// String indexDir = args[0];
// String q = args[1];
String indexDir = "D:\\Lucene\\Index";
String q = "txt2";
search(indexDir, q);
}

private static void search(String indexDir, String q) throws Exception {
Directory dir = FSDirectory.open(new File(indexDir));
IndexSearcher is = new IndexSearcher(dir);
QueryParser parser = new QueryParser(Version.LUCENE_30, "contents", new StandardAnalyzer(Version.LUCENE_30));
Query query = parser.parse(q);
long start = System.currentTimeMillis();
TopDocs hits = is.search(query, 10);
long end = System.currentTimeMillis();

System.err.print("Found" + hits.totalHits + "document(s) (in " + (end - start)
+ "milliseconds that matched query'" + q + "':");

for (ScoreDoc scoreDoc : hits.scoreDocs) {
Document doc = is.doc(scoreDoc.doc);
System.out.println(doc.get("fullpath"));

}
is.close();
}
}

执行结果如下:

Found1document(s) (in 9milliseconds that matched query'txt2':D:\Lucene\Data\record2.txt




推荐阅读
  • camel_使用Camel在来自不同来源的Solr中索引数据
    camelApacheSolr是建立在Lucene之上的“流行的,快速的开源企业搜索平台”。为了进行搜索(并查找结果),通常需要从不同的源(例如内容管理 ... [详细]
  • 大数据Hadoop生态(20)MapReduce框架原理OutputFormat的开发笔记
    本文介绍了大数据Hadoop生态(20)MapReduce框架原理OutputFormat的开发笔记,包括outputFormat接口实现类、自定义outputFormat步骤和案例。案例中将包含nty的日志输出到nty.log文件,其他日志输出到other.log文件。同时提供了一些相关网址供参考。 ... [详细]
  • ES基本原理名词解释In-memorybuffer:ES内存缓冲区,新建的document写入的地方document:索引和搜索的 ... [详细]
  • 本文由编程笔记#小编为大家整理,主要介绍了Nutch相关的知识,希望对你有一定的参考价值。 ... [详细]
  • 本文介绍了使用kotlin实现动画效果的方法,包括上下移动、放大缩小、旋转等功能。通过代码示例演示了如何使用ObjectAnimator和AnimatorSet来实现动画效果,并提供了实现抖动效果的代码。同时还介绍了如何使用translationY和translationX来实现上下和左右移动的效果。最后还提供了一个anim_small.xml文件的代码示例,可以用来实现放大缩小的效果。 ... [详细]
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • 本文介绍了Java工具类库Hutool,该工具包封装了对文件、流、加密解密、转码、正则、线程、XML等JDK方法的封装,并提供了各种Util工具类。同时,还介绍了Hutool的组件,包括动态代理、布隆过滤、缓存、定时任务等功能。该工具包可以简化Java代码,提高开发效率。 ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • Android系统移植与调试之如何修改Android设备状态条上音量加减键在横竖屏切换的时候的显示于隐藏
    本文介绍了如何修改Android设备状态条上音量加减键在横竖屏切换时的显示与隐藏。通过修改系统文件system_bar.xml实现了该功能,并分享了解决思路和经验。 ... [详细]
  • MyBatis多表查询与动态SQL使用
    本文介绍了MyBatis多表查询与动态SQL的使用方法,包括一对一查询和一对多查询。同时还介绍了动态SQL的使用,包括if标签、trim标签、where标签、set标签和foreach标签的用法。文章还提供了相关的配置信息和示例代码。 ... [详细]
  • web.py开发web 第八章 Formalchemy 服务端验证方法
    本文介绍了在web.py开发中使用Formalchemy进行服务端表单数据验证的方法。以User表单为例,详细说明了对各字段的验证要求,包括必填、长度限制、唯一性等。同时介绍了如何自定义验证方法来实现验证唯一性和两个密码是否相等的功能。该文提供了相关代码示例。 ... [详细]
  • mac php错误日志配置方法及错误级别修改
    本文介绍了在mac环境下配置php错误日志的方法,包括修改php.ini文件和httpd.conf文件的操作步骤。同时还介绍了如何修改错误级别,以及相应的错误级别参考链接。 ... [详细]
  • Struts2+Sring+Hibernate简单配置
    2019独角兽企业重金招聘Python工程师标准Struts2SpringHibernate搭建全解!Struts2SpringHibernate是J2EE的最 ... [详细]
  • python3 logging
    python3logginghttps:docs.python.org3.5librarylogging.html,先3.5是因为我当前的python版本是3.5之所 ... [详细]
  • Lucene系列四:Lucene提供的分词器、IKAnalyze中文分词器集成、扩展 IKAnalyzer的停用词和新词
    一、Lucene提供的分词器StandardAnalyzer和SmartChineseAnalyzer1.新建一个测试Lucene提供的分词器的maven项目LuceneAnal ... [详细]
author-avatar
可卡因
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有