Lucene和Solr学习总结(3)增删改查

使用IndexSearcher,IndexWriter对象对索引进行增删改查

直接贴代码了,方便日后查看,回顾

public class LuceneManager {

 

private IndexWriter getIndexWriter() throws IOException {

Directory directory = FSDirectory.open(new File("D://lucene//index"));//指定索引库存放位置Directory对象

Analyzer analyzer = new IKAnalyzer();

IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_10_3, analyzer);//指定分析器

IndexWriter indexWriter = new IndexWriter(directory, config);//创建IndexWriter

return indexWriter;

}

public IndexSearcher getIndexSearcher() throws Exception{

Directory directory = FSDirectory.open(new File("D://lucene//index"));

IndexReader r = DirectoryReader.open(directory);

return new IndexSearcher(r);

}

private void printResult(Query query,IndexSearcher indexSearcher) throws IOException {

TopDocs search = indexSearcher.search(query, 10);

for (ScoreDoc scoreDao : search.scoreDocs) {

int doc = scoreDao.doc;

Document document = indexSearcher.doc(doc);

 System.out.println(document.get("fielName"));

           //文件内容

         //  System.out.println(document.get("file_content"));

           //文件大小

           System.out.println(document.get("fileSize"));

           //文件路径

           System.out.println(document.get("filePath"));

           System.out.println("=============");

}

}

@Test

public void testDeleteAll() throws Exception {

IndexWriter indexWriter = getIndexWriter();

indexWriter.deleteAll();//删除所有

indexWriter.close();

}

//按条件删除

@Test

public void testDelete() throws Exception{

IndexWriter indexWriter = getIndexWriter();

Query query = new TermQuery(new Term("fielName","apache"));

indexWriter.deleteDocuments(query);

indexWriter.close();

}

//修改,删掉一个在添加一个

@Test

public void testUpdate() throws Exception{

IndexWriter indexWriter = getIndexWriter();

Document doc = new Document();

doc.add(new TextField("fielName", "测试更新", Store.YES));

//先删,再添加

indexWriter.updateDocument(new Term("fielName","lucene"), doc,new IKAnalyzer());

indexWriter.close();

}

/*

 * 使用Query的子类进行查询

 */

//查所有

@Test

public void findAll() throws Exception {

IndexSearcher indexSearcher = getIndexSearcher();

Query query = new MatchAllDocsQuery();

System.out.println(query);

printResult(query, indexSearcher);

//idnexSearch是通过构造创建,里面包含indexReader,可以这样关流

indexSearcher.getIndexReader().close();

}

 

//根据数值范围查

@Test

public void findByNumeriRangeQuery() throws Exception{

IndexSearcher indexSearcher = getIndexSearcher();

Query query = NumericRangeQuery.newLongRange("fileSize", 0L, 200L, true, false);//是否包含最大和最小值

System.out.println(query);

printResult(query, indexSearcher);

//idnexSearch是通过构造创建,里面包含indexReader,可以这样关流

indexSearcher.getIndexReader().close();

}

//组合查询 BooleanQuery

@Test

public void testBooleanQuery() throws Exception {

IndexSearcher indexSearcher = getIndexSearcher();

Query query1 = new TermQuery(new Term("fielName","apache"));

Query query2 = new TermQuery(new Term("fielName","lucene"));

/*

 * 域值 +fielName:apache fielName:lucene

 * MUST中域值前面带一个+,MUST_NOT是-号,should是空格

 * must相当于and   shuoud相当于or  must_not相当于!(非)

 */

BooleanQuery bq = new BooleanQuery();

bq.add(query1, Occur.MUST_NOT);//必须,相当于and条件

bq.add(query2,Occur.MUST);//应该,

System.out.println(bq);

printResult(bq, indexSearcher);

indexSearcher.getIndexReader().close();

}

/*

 * 使用queryparser查询

 * 通过QueryParser也可以创建Query,

 * QueryParser提供一个Parse方法,

 * 此方法可以直接根据查询语法来查询。

 * Query对象执行的查询语法可通过System.out.println(query);

 */

@Test

public void testQueryParse() throws Exception{

IndexSearcher searcher = getIndexSearcher();

//第一个参数默认搜索的域

String f = "fielName";

QueryParser queryParser = new QueryParser(f, new IKAnalyzer());

Query query = queryParser.parse("apache and java");//AND是关键字,会使用语法查询

searcher.search(query, 10);

printResult(query, searcher);

searcher.getIndexReader().close();

}

//指定多个默认域查询 MultiFieldQueryParser

@Test

public void testMultiField() throws Exception {

IndexSearcher indexSearcher = getIndexSearcher();

String[] f = {"fielName","fielContent"};

MultiFieldQueryParser fieldQueryParser = new MultiFieldQueryParser(f, new IKAnalyzer());

Query query = fieldQueryParser.parse("lucene AND lucene");

indexSearcher.search(query, 10);

printResult(query, indexSearcher);

indexSearcher.getIndexReader().close();

}

}

public class LuceneManager {
private IndexWriter getIndexWriter() throws IOException {Directory directory = FSDirectory.open(new File("D://lucene//index"));//指定索引库存放位置Directory对象Analyzer analyzer = new IKAnalyzer();IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_10_3, analyzer);//指定分析器IndexWriter indexWriter = new IndexWriter(directory, config);//创建IndexWriterreturn indexWriter;}public IndexSearcher getIndexSearcher() throws Exception{Directory directory = FSDirectory.open(new File("D://lucene//index"));IndexReader r = DirectoryReader.open(directory);return new IndexSearcher(r);}private void printResult(Query query,IndexSearcher indexSearcher) throws IOException {TopDocs search = indexSearcher.search(query, 10);for (ScoreDoc scoreDao : search.scoreDocs) {int doc = scoreDao.doc;Document document = indexSearcher.doc(doc); System.out.println(document.get("fielName"));           //文件内容         //  System.out.println(document.get("file_content"));           //文件大小           System.out.println(document.get("fileSize"));           //文件路径           System.out.println(document.get("filePath"));           System.out.println("=============");}}@Testpublic void testDeleteAll() throws Exception {IndexWriter indexWriter = getIndexWriter();indexWriter.deleteAll();//删除所有indexWriter.close();}//按条件删除@Testpublic void testDelete() throws Exception{IndexWriter indexWriter = getIndexWriter();Query query = new TermQuery(new Term("fielName","apache"));indexWriter.deleteDocuments(query);indexWriter.close();}//修改,删掉一个在添加一个@Testpublic void testUpdate() throws Exception{IndexWriter indexWriter = getIndexWriter();Document doc = new Document();doc.add(new TextField("fielName", "测试更新", Store.YES));//先删,再添加indexWriter.updateDocument(new Term("fielName","lucene"), doc,new IKAnalyzer());indexWriter.close();}/* * 使用Query的子类进行查询 *///查所有@Testpublic void findAll() throws Exception {IndexSearcher indexSearcher = getIndexSearcher();Query query = new MatchAllDocsQuery();System.out.println(query);printResult(query, indexSearcher);//idnexSearch是通过构造创建,里面包含indexReader,可以这样关流indexSearcher.getIndexReader().close();}
//根据数值范围查@Testpublic void findByNumeriRangeQuery() throws Exception{IndexSearcher indexSearcher = getIndexSearcher();Query query = NumericRangeQuery.newLongRange("fileSize", 0L, 200L, true, false);//是否包含最大和最小值System.out.println(query);printResult(query, indexSearcher);//idnexSearch是通过构造创建,里面包含indexReader,可以这样关流indexSearcher.getIndexReader().close();}//组合查询 [email protected] void testBooleanQuery() throws Exception {IndexSearcher indexSearcher = getIndexSearcher();Query query1 = new TermQuery(new Term("fielName","apache"));Query query2 = new TermQuery(new Term("fielName","lucene"));/* * 域值 +fielName:apache fielName:lucene * MUST中域值前面带一个+,MUST_NOT是-号,should是空格 * must相当于and   shuoud相当于or  must_not相当于!(非) */BooleanQuery bq = new BooleanQuery();bq.add(query1, Occur.MUST_NOT);//必须,相当于and条件bq.add(query2,Occur.MUST);//应该,System.out.println(bq);printResult(bq, indexSearcher);indexSearcher.getIndexReader().close();}/* * 使用queryparser查询 * 通过QueryParser也可以创建Query, * QueryParser提供一个Parse方法, * 此方法可以直接根据查询语法来查询。 * Query对象执行的查询语法可通过System.out.println(query); */@Testpublic void testQueryParse() throws Exception{IndexSearcher searcher = getIndexSearcher();//第一个参数默认搜索的域String f = "fielName";QueryParser queryParser = new QueryParser(f, new IKAnalyzer());Query query = queryParser.parse("apache and java");//AND是关键字,会使用语法查询searcher.search(query, 10);printResult(query, searcher);searcher.getIndexReader().close();}//指定多个默认域查询 [email protected] void testMultiField() throws Exception {IndexSearcher indexSearcher = getIndexSearcher();String[] f = {"fielName","fielContent"};MultiFieldQueryParser fieldQueryParser = new MultiFieldQueryParser(f, new IKAnalyzer());Query query = fieldQueryParser.parse("lucene AND lucene");indexSearcher.search(query, 10);printResult(query, indexSearcher);indexSearcher.getIndexReader().close();}}

原文地址:https://www.cnblogs.com/a-small-lyf/p/10008872.html

时间: 2024-10-10 23:10:41

Lucene和Solr学习总结(3)增删改查的相关文章

MyBatis学习--简单的增删改查

jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: 1 Public static void main(String[] args) { 2 Connection connection = null; 3 PreparedStatement preparedStatement = null; 4 ResultSet resultSet = null; 5 6 try { 7 //加载数据库驱动 8 Class.forName

mybatis学习之普通增删改查

mybatis下载地址:https://github.com/mybatis/mybatis-3/releases 选择你要下载的版本,这里我下载的3.4.2版 项目结构: 将mybatis中的所有jar包导入还要导入链接mysql数据库的jar包. 其中db.properties,mybatis-config.xml,log4j.properties是在src下. 在mysql中新建mybatis数据库,在数据库中新建表t_customer,表结构如下: 随后向其中随便插入几条数据. Cust

【转载】ASP.NET MVC Web API 学习笔记---联系人增删改查

本章节简单介绍一下使用ASP.NET MVC Web API 做增删改查.目前很多Http服务还是通过REST或者类似RESP的模型来进行数据操作的.下面我们通过创建一个简单的Web API来管理联系人 说明:为了方便数据不使用真正的数据库,而是通过内存数据模拟 1.       Web API中包含的方法 Action HTTP method Relative URI GetAllContact GET /api/contact GetContact GET /api/contact /id

EF学习笔记——通用增删改查方案

http://blog.csdn.net/leftfist/article/details/25005307 我刚接触EF未久,还不知道它有什么强大之处,但看上去,EF提供了一般的增删改查功能.以往用过一些ORM方法,尽管有代码生成器,但代码量总的 来说比较多.这次采用EF,我就想,能不能尽量写出一些通用的方法,以后添加表.实体类,只需做很少的改动,就能拥有基本的增删改查功能呢? 方案如下: 1. 分为几个部分:BLL.DAL.Model.Interface.其中,EF生成的代码放在Model.

MyBatis学习之简单增删改查操作、MyBatis存储过程、MyBatis分页、MyBatis一对一、MyBatis一对多

一.用到的实体类如下: Student.java [html] view plaincopy package com.company.entity; import java.io.Serializable; import java.util.Date; public class Student implements Serializable{ private static final long serialVersionUID = 1L; private int id; private Stri

python之MySQL学习——简单的增删改查封装

1.增删改查封装类MysqlHelper.py 1 import pymysql as ps 2 3 class MysqlHelper: 4 def __init__(self, host, user, password, database, charset): 5 self.host = host 6 self.user = user 7 self.password = password 8 self.database = database 9 self.charset = charset

[PHP][thinkphp5] 学习一:增删改查

1 <?php 2 namespace app\index\controller; 3 4 use think\Controller; 5 use think\Db; 6 7 class Test extends Controller 8 { 9 10 public function index() 11 { 12 $name ="Hello word TP5"; 13 14 $this->assign('name',$name); 15 16 return $this-&

python学习-字典的增删改查

1 dic1 = {'name':'paoche', 2 'age':19, 3 'active':['beijing','hebei'], 4 'id':{'wangyi':'skmdod008b', 5 'sina':'skmdod00bc' 6 } 7 } 一.字典的增 方法1:直接新增键值对,若无此键则新增键值对,有此键则修改值 1 dic1['high'] = 180 #没有键值对,则追加 2 dic1['age'] = 30 #有键值,则修改 3 print(dic1) 4 "&qu

mybatis学习之二 增删改查

1.配置映射文件grilsMapper.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="mappe