创建索引之代码开发

【创建索引库】

使用indexwriter对象创建索引。

【实现步骤】

(1)创建一个java工程,并导入jar包。

(2)创建一个indexwriter对象。

1)指定索引库的存放位置Directory对象。

2)指定一个分析器,对文档内容进行分析。

(3)创建Document对象

(4)创建filed对象,将field添加到Document对象中。

(5)使用indexwriter对象将Document对象写入到索引库,此过程进行索引创建,并将索引和Document对象写入索引库。

(6)关闭IndexWriter对象。

FirstLucene.java:

  1 package com.itheima.lucene;
  2
  3 import static org.junit.Assert.*;
  4 import java.io.File;
  5 import org.apache.commons.io.FileUtils;
  6 import org.apache.lucene.analysis.Analyzer;
  7 import org.apache.lucene.analysis.TokenStream;
  8 import org.apache.lucene.analysis.cjk.CJKAnalyzer;
  9 import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
 10 import org.apache.lucene.analysis.standard.StandardAnalyzer;
 11 import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
 12 import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
 13 import org.apache.lucene.document.Document;
 14 import org.apache.lucene.document.Field;
 15 import org.apache.lucene.document.Field.Store;
 16 import org.apache.lucene.document.LongField;
 17 import org.apache.lucene.document.StoredField;
 18 import org.apache.lucene.document.TextField;
 19 import org.apache.lucene.index.DirectoryReader;
 20 import org.apache.lucene.index.IndexReader;
 21 import org.apache.lucene.index.IndexWriter;
 22 import org.apache.lucene.index.IndexWriterConfig;
 23 import org.apache.lucene.index.Term;
 24 import org.apache.lucene.search.IndexSearcher;
 25 import org.apache.lucene.search.Query;
 26 import org.apache.lucene.search.ScoreDoc;
 27 import org.apache.lucene.search.TermQuery;
 28 import org.apache.lucene.search.TopDocs;
 29 import org.apache.lucene.store.Directory;
 30 import org.apache.lucene.store.FSDirectory;
 31 import org.apache.lucene.store.RAMDirectory;
 32 import org.apache.lucene.util.Version;
 33 import org.junit.Test;
 34 import org.wltea.analyzer.lucene.IKAnalyzer;
 35
 36 public class FirstLucene {
 37
 38     // 创建索引
 39     @Test
 40     public void testIndex() throws Exception {
 41         // 第一步:创建一个java工程,并导入jar包。
 42         // 第二步:创建一个indexwriter对象。
 43         Directory directory = FSDirectory.open(new File("D:\\temp\\index"));
 44         // Directory directory = new RAMDirectory();//保存索引到内存中 (内存索引库)
 45         //Analyzer analyzer = new StandardAnalyzer();// 官方推荐
 46         Analyzer analyzer = new IKAnalyzer();// 官方推荐
 47         IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, analyzer);
 48         IndexWriter indexWriter = new IndexWriter(directory, config);
 49         // 1)指定索引库的存放位置Directory对象
 50         // 2)指定一个分析器,对文档内容进行分析。
 51         // 第三步:创建field对象,将field添加到document对象中。
 52         File f = new File("D:\\Lucene&solr\\searchsource");
 53         File[] listFiles = f.listFiles();
 54         for (File file : listFiles) {
 55             // 第三步:创建document对象。
 56             Document document = new Document();
 57             // 文件名称
 58             String file_name = file.getName();
 59             Field fileNameField = new TextField("fileName", file_name, Store.YES);
 60             // 文件大小
 61             long file_size = FileUtils.sizeOf(file);
 62             Field fileSizeField = new LongField("fileSize", file_size, Store.YES);
 63             // 文件路径
 64             String file_path = file.getPath();
 65             Field filePathField = new StoredField("filePath", file_path);
 66             // 文件内容
 67             String file_content = FileUtils.readFileToString(file);
 68             Field fileContentField = new TextField("fileContent", file_content, Store.NO);
 69
 70             document.add(fileNameField);
 71             document.add(fileSizeField);
 72             document.add(filePathField);
 73             document.add(fileContentField);
 74             // 第四步:使用indexwriter对象将document对象写入索引库,此过程进行索引创建。并将索引和document对象写入索引库。
 75             indexWriter.addDocument(document);
 76
 77         }
 78         // 第五步:关闭IndexWriter对象。
 79         indexWriter.close();
 80     }
 81
 82     // 搜索索引
 83     @Test
 84     public void testSearch() throws Exception {
 85         // 第一步:创建一个Directory对象,也就是索引库存放的位置。
 86         Directory directory = FSDirectory.open(new File("D:\\temp\\index"));// 磁盘
 87         // 第二步:创建一个indexReader对象,需要指定Directory对象。
 88         IndexReader indexReader = DirectoryReader.open(directory);
 89         // 第三步:创建一个indexsearcher对象,需要指定IndexReader对象
 90         IndexSearcher indexSearcher = new IndexSearcher(indexReader);
 91         // 第四步:创建一个TermQuery对象,指定查询的域和查询的关键词。
 92         Query query = new TermQuery(new Term("fileName", "lucene"));
 93         // 第五步:执行查询。
 94         TopDocs topDocs = indexSearcher.search(query, 10);
 95         // 第六步:返回查询结果。遍历查询结果并输出。
 96         ScoreDoc[] scoreDocs = topDocs.scoreDocs;
 97         for (ScoreDoc scoreDoc : scoreDocs) {
 98             int doc = scoreDoc.doc;
 99             Document document = indexSearcher.doc(doc);
100             // 文件名称
101             String fileName = document.get("fileName");
102             System.out.println(fileName);
103             // 文件内容
104             String fileContent = document.get("fileContent");
105             System.out.println(fileContent);
106             // 文件大小
107             String fileSize = document.get("fileSize");
108             System.out.println(fileSize);
109             // 文件路径
110             String filePath = document.get("filePath");
111             System.out.println(filePath);
112             System.out.println("------------");
113         }
114         // 第七步:关闭IndexReader对象
115         indexReader.close();
116
117     }
118
119     // 查看标准分析器的分词效果
120     @Test
121     public void testTokenStream() throws Exception {
122         // 创建一个标准分析器对象
123 //        Analyzer analyzer = new StandardAnalyzer();
124 //        Analyzer analyzer = new CJKAnalyzer();
125 //        Analyzer analyzer = new SmartChineseAnalyzer();
126         Analyzer analyzer = new IKAnalyzer();
127         // 获得tokenStream对象
128         // 第一个参数:域名,可以随便给一个
129         // 第二个参数:要分析的文本内容
130 //        TokenStream tokenStream = analyzer.tokenStream("test",
131 //                "The Spring Framework provides a comprehensive programming and configuration model.");
132         TokenStream tokenStream = analyzer.tokenStream("test",
133                 "高富帅可以用二维表结构来逻辑表达实现的数据");
134         // 添加一个引用,可以获得每个关键词
135         CharTermAttribute charTermAttribute = tokenStream.addAttribute(CharTermAttribute.class);
136         // 添加一个偏移量的引用,记录了关键词的开始位置以及结束位置
137         OffsetAttribute offsetAttribute = tokenStream.addAttribute(OffsetAttribute.class);
138         // 将指针调整到列表的头部
139         tokenStream.reset();
140         // 遍历关键词列表,通过incrementToken方法判断列表是否结束
141         while (tokenStream.incrementToken()) {
142             // 关键词的起始位置
143             System.out.println("start->" + offsetAttribute.startOffset());
144             // 取关键词
145             System.out.println(charTermAttribute);
146             // 结束位置
147             System.out.println("end->" + offsetAttribute.endOffset());
148         }
149         tokenStream.close();
150     }
151
152 }

原文地址:https://www.cnblogs.com/zhzcode/p/9784241.html

时间: 2024-08-30 12:41:48

创建索引之代码开发的相关文章

一、创建索引之代码开发

jar包: Lucene包: lucene-core-4.10.3.jar lucene-analyzers-common-4.10.3.jar lucene-queryparser-4.10.3.jar 其它: commons-io-2.4.jar junit-4.9.jar package com.itheima.lucene; import java.io.File; import java.io.IOException; import org.apache.commons.io.File

SQLSERVER 创建索引实现代码

是SQL Server编排数据的内部方法.它为SQL Server提供一种方法来编排查询数据 什么是索引 拿汉语字典的目录页(索引)打比方:正如汉语字典中的汉字按页存放一样,SQL Server中的数据记录也是按页存放的,每页容量一般为4K.为了加快查找的速度,汉语字(词)典一般都有按拼音.笔画.偏旁部首等排序的目录(索引),我们可以选择按拼音或笔画查找方式,快速查找到需要的字(词). 同理,SQL Server允许用户在表中创建索引,指定按某列预先排序,从而大大提高查询速度. ? SQL Se

mysql创建索引

在数据库表中,对字段建立索引可以大大提高查询速度.假如我们创建了一个 mytable表: 复制代码 代码如下: CREATE TABLE mytable(   ID INT NOT NULL,    username VARCHAR(16) NOT NULL  ); 我们随机向里面插入了10000条记录,其中有一条:5555, admin. 在查找username="admin"的记录 SELECT * FROM mytable WHERE username='admin';时,如果在

Mysql运维管理-创建索引知识及创建索引的多种方法实战9

为表的字段创建索引 索引就像书的目录一样,如果在字段上建立索引,那么以索引为条件时可以加快查询数据的速度. 1 创建主键索引 查询数据库的内容,按主键查询是最快的,每个表只能有一个主键,但是可以有多个普通索引列,主键列要求所有内容必须唯一,而索引列不要求内容唯一.我们无论建立主键索引还是普通索引,都要在表的对应列上创建,可以对单列创建索引也可以对多列创建索引建立主键索方法: 1.在创建表时,可以增加建立主键索引语句 [email protected] 04:0932->create table

Lucene.net 从创建索引到搜索的代码范例

关于Lucene.Net的介绍网上已经很多了在这里就不多介绍Lucene.Net主要分为建立索引,维护索引和搜索索引Field.Store的作用是通过全文检查就能返回对应的内容,而不必再通过id去DB中加载.Field.Store.YES:存储字段值(未分词前的字段值)Field.Store.NO:不存储,存储与索引没有关系Field.Store.COMPRESS:压缩存储,用于长文本或二进制,但性能受损Field.Index.ANALYZED:分词建索引 Field.Index.ANALYZE

基于lucene的案例开发:创建索引

转载请注明出处:http://blog.csdn.net/xiaojimanman/article/details/42872711 从这篇博客开始,不论是API介绍还是后面的案例开发,都是基于 lucene4.3.1 这个版本,Lucene4.3.1 下载请点击这里, Lucene其他版本下载请点击这里,Lucene4.3.1官方API文档请点击这里. 创建索引demo 在开始介绍之前,先看一个简单的索引创建demo程序: /** *@Description: 索引创建demo */ pack

lucene之创建索引代码

public void createIndex() throws IOException { // 第一步采集数据:(jdbc采集数据) BookDao dao = new BookDaoImpl(); List<Book> queryBookList = dao.queryBookList(); // 将数据采集放到docment对象中 Document doc = null; List<Document> docList = new ArrayList<>(); f

Elasticsearch搜索API使用一:创建索引并指定索引类型的mapping

ES默认是动态创建索引和索引类型的mapping的.这就相当于无需定义Solr中的Schema,无需指定各个字段的索引规则就可以索引文件,很方便.但有时方便就代表着不灵活.比如,ES默认一个字段是要做分词的,但我们有时要搜索匹配整个字段却不行.如有统计工作要记录每个城市出现的次数.对于NAME字段,若记录"new york"文本,ES可能会把它拆分成"new"和"york"这两个词,分别计算这个两个单词的次数,而不是我们期望的"new

jQuery代码开发技巧收集,jquery常用的开发代码

jQuery代码开发技巧收集,jquery常用的开发代码 今天分享一个jquery常用的开发代码,大部分是网友总结的,总共60条.后期我也会陆续完善! 把我在开发中常用的写在这里,希望持续关注~~ 1. 使用siblings()来处理同类元素 // Rather than doing this $('#nav li').click(function(){ $('#nav li').removeClass('active'); $(this).addClass('active'); }); //