Lucene创建索引与搜索索引试手

2023-10-08 04:18

本文主要是介绍Lucene创建索引与搜索索引试手,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

由于仿写的源码的版本是Lucene2.1.0,我用的Lucene已经是4.5.0了,所以像创建IndexWriter、IndexSearcher的时候源码的已经不能用了,只好自己查api摸索,所以有个老师在旁边指导该多好。


首先我创建的是中文的索引。

CJKAnalyzer是:对中文汉字,每两个字作为一个词条

StandardAnalyzer是:单个汉字作为一个词条

所以如果要查询像:“大禹”这样俩个字的词条时,用CJKAnalyzer,查询像“水”这样的词条时,需要改用StandardAnalyzer。我在这里纠结了很久不知道哪里错了。


还有就是StringField和TextField的区别。api的解释分别是:

TextFieldA field that is indexed and tokenized, without term vectors. For example this would be used on a 'body' field, that contains the bulk of a document's text.

StringField:A field that is indexed but not tokenized: the entire String value is indexed as a single token. For example this might be used for a 'country' field or an 'id' field, or any field that you intend to use for sorting or access through the field cache.

现在看看也没很多错的地方,但是写了仨小时。期间各种查api啊,还是那句话,有个老师指点一下的话,我就能少走很多弯路,节省很多时间了。唉。。。

package org.apache.lucene;import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;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;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;import com.wb.tool.FileList;
import com.wb.tool.FileText;public class LuceneIndexer {private JTextField jtfa;private JButton jba;private JTextField jtfb;private JButton jbb;private JButton jbc;private static JTextArea jta;private void createAndShowGUI(){// 设置跨平台外观感觉//String lf=UIManager.getCrossPlatformLookAndFeelClassName();//GTK//String lf="com.sun.java.swing.plaf.gtk.GTKLookAndFeel";//System//String lf=UIManager.getSystemLookAndFeelClassName();//windows//String lf="com.sun.java.swing.plaf.windows.WindowsLookAndFeel";//metal//String lf="javax.swing.plaf.metal.MetalLookAndFeel";/**common usetry{UIManager.setLookAndFeel(lf);}catch(Exception ce){JOptionPane.showMessageDialog(null,"无法设定外观感觉!");}**///Java感觉JFrame.setDefaultLookAndFeelDecorated(true);JFrame frame=new JFrame("TEST");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);final JFileChooser fc=new JFileChooser();fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);Container con= frame.getContentPane();	con.setLayout(new BorderLayout());JPanel jpup=new JPanel();jpup.setLayout(new GridLayout(3,2));jtfa=new JTextField(30);jba=new JButton("选择被索引的文件存放路径");jba.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){int r=fc.showOpenDialog(null);if(r==JFileChooser.APPROVE_OPTION){jtfa.setText(fc.getSelectedFile().getPath());jbc.setEnabled(true);}}	});jtfb=new JTextField(30);JButton jbb=new JButton("选择索引的存放路径");jbb.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){int r=fc.showOpenDialog(null);if(r==JFileChooser.APPROVE_OPTION){jtfb.setText(fc.getSelectedFile().getPath());jbc.setEnabled(true);}}	});JLabel jl=new JLabel("");jbc=new JButton("建立索引");jbc.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){try{LuceneIndexerTool.index(jtfa.getText(),jtfb.getText());//jbc.setEnabled(false);}catch(Exception ee){ee.printStackTrace();jbc.setEnabled(true);JOptionPane.showMessageDialog(null,"索引创建失败!");System.out.println(ee.getMessage());}}	});jpup.add(jtfa);jpup.add(jba);jpup.add(jtfb);jpup.add(jbb);jpup.add(jl);jpup.add(jbc);jta=new JTextArea(10,60);JScrollPane jsp=new JScrollPane(jta);con.add(jpup,BorderLayout.NORTH);con.add(jsp,BorderLayout.CENTER);frame.setSize(200,100);frame.pack();frame.setVisible(true);}public static void main(String[] args) {SwingUtilities.invokeLater(new Runnable() {public void run() {new LuceneIndexer().createAndShowGUI();}});}static class LuceneIndexerTool {public static void index(String filePath, String indexPath) throws IOException {Path path = Paths.get(indexPath);Directory dir = FSDirectory.open(path);Analyzer analyzer = new StandardAnalyzer();IndexWriterConfig config = new IndexWriterConfig(analyzer);IndexWriter writer = new IndexWriter(dir, config);String s[] = FileList.getFiles(filePath);int len = s.length;for(int i=0; i<len; i++) {File file = new File(s[i]);String ext = getExt(file);if((ext.equalsIgnoreCase("htm")) || (ext.equalsIgnoreCase("html"))) {Document doc = new Document();Field field;String fileName = file.getName();field = new TextField("fileName", fileName, Field.Store.YES);doc.add(field);String uri = file.getPath();field = new TextField("uri", uri, Field.Store.YES);doc.add(field);Date dt = new Date(file.lastModified());SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");String date = sdf.format(dt);field = new TextField("date", date, Field.Store.YES);doc.add(field);double l = file.length();String size = "";if(l>1024)size = String.valueOf(Math.floor(l/1024)) + "K";elsesize = String.valueOf(size) + "Bytes";field = new TextField("size", size, Field.Store.YES);doc.add(field);String text = FileText.getText(file);field = new TextField("text", text, Field.Store.YES);doc.add(field);String digest = "";if(text.length() > 200)digest = text.substring(0, 200);elsedigest = text;field = new TextField("digest", digest, Field.Store.YES);doc.add(field);writer.addDocument(doc);jta.setText(jta.getText() + "已经加入索引:" + file + "\n");}}writer.close();}public static String getExt(File file) {String s = file.getName();s = s.substring(s.lastIndexOf(".") + 1);return s;}}}
</pre><pre name="code" class="java"><pre name="code" class="java">package org.apache.lucene;import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;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;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.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;public class LuceneSearcher {private JTextField jtfa;private JButton jba;private JTextField jtfb;private JButton jbb;private JButton jbc;private static JTextArea jta;private JTextField jtfc;private JButton jbd;private JButton jbe;private void createAndShowGUI(){// 设置跨平台外观感觉//String lf=UIManager.getCrossPlatformLookAndFeelClassName();//GTK//String lf="com.sun.java.swing.plaf.gtk.GTKLookAndFeel";//System//String lf=UIManager.getSystemLookAndFeelClassName();//windows//String lf="com.sun.java.swing.plaf.windows.WindowsLookAndFeel";//metal//String lf="javax.swing.plaf.metal.MetalLookAndFeel";/**common usetry{UIManager.setLookAndFeel(lf);}catch(Exception ce){JOptionPane.showMessageDialog(null,"无法设定外观感觉!");}**///Java感觉JFrame.setDefaultLookAndFeelDecorated(true);JFrame frame=new JFrame("Tianen Searcher! yutianen@163.com");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);final JFileChooser fc=new JFileChooser();fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);Container con= frame.getContentPane();	con.setLayout(new BorderLayout());JPanel jpup=new JPanel();jpup.setLayout(new GridLayout(2,2));jtfa=new JTextField(30);jba=new JButton("选择索引的存放路径");jba.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){int r=fc.showOpenDialog(null);if(r==JFileChooser.APPROVE_OPTION){jtfa.setText(fc.getSelectedFile().getPath());}}	});jtfb=new JTextField(30);JButton jbb=new JButton("搜索");jbb.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){try{String indexPath=jtfa.getText();String phrase=jtfb.getText();new LuceneSearcherTool().search(phrase,indexPath);
System.out.println("123");}catch(Exception ex){JOptionPane.showMessageDialog(null,"搜索失败!","提示",JOptionPane.ERROR_MESSAGE);}}	});jpup.add(jtfa);jpup.add(jba);jpup.add(jtfb);jpup.add(jbb);jta=new JTextArea(10,30);	JScrollPane jsp=new JScrollPane(jta);JPanel jpdown=new JPanel();jpdown.setLayout(new FlowLayout());		jtfc=new JTextField(35);jbd=new JButton("设定导出路径");fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);jbd.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){int r=fc.showOpenDialog(null);if(r==JFileChooser.APPROVE_OPTION){jtfc.setText(fc.getSelectedFile().getPath());}}	});jbe=new JButton("导出搜索结果");jbe.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){try{File f=new File(jtfc.getText());FileWriter fw=new FileWriter(f);PrintWriter pw=new PrintWriter(fw);pw.write(jta.getText());pw.flush();pw.close();							JOptionPane.showMessageDialog(null,"写入文件成功!","提示",JOptionPane.INFORMATION_MESSAGE);}catch(IOException ioe){JOptionPane.showMessageDialog(null,"写入文件失败!","提示",JOptionPane.ERROR_MESSAGE);}}	});jpdown.add(jtfc);jpdown.add(jbd);jpdown.add(jbe);con.add(jpup,BorderLayout.NORTH);con.add(jsp,BorderLayout.CENTER);con.add(jpdown,BorderLayout.SOUTH);frame.setSize(200,100);frame.pack();frame.setVisible(true);}public static void main(String[] args) {SwingUtilities.invokeLater(new Runnable() {public void run() {new LuceneSearcher().createAndShowGUI();}});}static class LuceneSearcherTool {public void search(String phrase, String indexPath) throws IOException, ParseException {Path path = Paths.get(indexPath);Directory dir = FSDirectory.open(path);IndexReader ir = DirectoryReader.open(dir);IndexSearcher is = new IndexSearcher(ir);Analyzer analyzer = new StandardAnalyzer();QueryParser parser = new QueryParser("text", analyzer);Query query = parser.parse(phrase);TopDocs hits = is.search(query, 10);for(ScoreDoc scoreDoc: hits.scoreDocs) {Document doc = is.doc(scoreDoc.doc);if(doc == null)continue;Field field = (Field) doc.getField("fileName");String fileName = field.stringValue();field = (Field) doc.getField("uri");String uri = field.stringValue();field = (Field) doc.getField("date");String date = field.stringValue();field = (Field) doc.getField("digest");String digest = field.stringValue();StringBuffer sb = new StringBuffer();sb.append("URI:" + uri + "\n");sb.append("filename:" + fileName + "\n");sb.append("date:" + date + "\n");sb.append("digest:" + digest + "\n");sb.append("------------------------------------\n");jta.setText(jta.getText() + sb.toString());}ir.close();dir.close();}}}


 


这篇关于Lucene创建索引与搜索索引试手的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/162624

相关文章

Python在二进制文件中进行数据搜索的实战指南

《Python在二进制文件中进行数据搜索的实战指南》在二进制文件中搜索特定数据是编程中常见的任务,尤其在日志分析、程序调试和二进制数据处理中尤为重要,下面我们就来看看如何使用Python实现这一功能吧... 目录简介1. 二进制文件搜索概述2. python二进制模式文件读取(rb)2.1 二进制模式与文本

C#高效实现在Word文档中自动化创建图表的可视化方案

《C#高效实现在Word文档中自动化创建图表的可视化方案》本文将深入探讨如何利用C#,结合一款功能强大的第三方库,实现在Word文档中自动化创建图表,为你的数据呈现和报告生成提供一套实用且高效的解决方... 目录Word文档图表自动化:为什么选择C#?从零开始:C#实现Word文档图表的基本步骤深度优化:C

Python列表的创建与删除的操作指南

《Python列表的创建与删除的操作指南》列表(list)是Python中最常用、最灵活的内置数据结构之一,它支持动态扩容、混合类型、嵌套结构,几乎无处不在,但你真的会创建和删除列表吗,本文给大家介绍... 目录一、前言二、列表的创建方式1. 字面量语法(最常用)2. 使用list()构造器3. 列表推导式

JavaWeb项目创建、部署、连接数据库保姆级教程(tomcat)

《JavaWeb项目创建、部署、连接数据库保姆级教程(tomcat)》:本文主要介绍如何在IntelliJIDEA2020.1中创建和部署一个JavaWeb项目,包括创建项目、配置Tomcat服务... 目录简介:一、创建项目二、tomcat部署1、将tomcat解压在一个自己找得到路径2、在idea中添加

Java利用Spire.Doc for Java实现在模板的基础上创建Word文档

《Java利用Spire.DocforJava实现在模板的基础上创建Word文档》在日常开发中,我们经常需要根据特定数据动态生成Word文档,本文将深入探讨如何利用强大的Java库Spire.Do... 目录1. Spire.Doc for Java 库介绍与安装特点与优势Maven 依赖配置2. 通过替换

java创建xls文件放到指定文件夹中实现方式

《java创建xls文件放到指定文件夹中实现方式》本文介绍了如何在Java中使用ApachePOI库创建和操作Excel文件,重点是如何创建一个XLS文件并将其放置到指定文件夹中... 目录Java创建XLS文件并放到指定文件夹中步骤一:引入依赖步骤二:创建XLS文件总结Java创建XLS文件并放到指定文件

Elasticsearch 的索引管理与映射配置实战指南

《Elasticsearch的索引管理与映射配置实战指南》在本文中,我们深入探讨了Elasticsearch中索引与映射的基本概念及其重要性,通过详细的操作示例,我们了解了如何创建、更新和删除索引,... 目录一、索引操作(一)创建索引(二)删除索引(三)关闭索引(四)打开索引(五)索引别名二、映射操作(一

MySQL索引踩坑合集从入门到精通

《MySQL索引踩坑合集从入门到精通》本文详细介绍了MySQL索引的使用,包括索引的类型、创建、使用、优化技巧及最佳实践,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友... 目录mysql索引完整教程:从入门到入土(附实战踩坑指南)一、索引是什么?为什么需要它?1.1 什么

Mysql数据库聚簇索引与非聚簇索引举例详解

《Mysql数据库聚簇索引与非聚簇索引举例详解》在MySQL中聚簇索引和非聚簇索引是两种常见的索引结构,它们的主要区别在于数据的存储方式和索引的组织方式,:本文主要介绍Mysql数据库聚簇索引与非... 目录前言一、核心概念与本质区别二、聚簇索引(Clustered Index)1. 实现原理(以 Inno

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三