lucene入门程序

b2d04a03f8b9e155ea6076f55897b7b8_0e26ab3e-a83e-4f0a-95af-d9589e04a560.jpg{{{width="auto" height="auto"}}}

导入需要的库文件:

3、创建索引

4、创建分词

5、创建索引配置

6、 指定索引库地址

7、通过IndexWriter对象将Document写入到索引库中

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;
 
import com.ssm.demo.pojo.Items;
import com.ssm.demo.service.ItemsService;
 /\*\*
  \* 入门demo
  \*
  \* @author liwei
  \*/
publicclass IndexManager extends LoadingSpringCfg {
     /\*\*
      \* 创建索引
      \*
      \* @throws Exception
      \*/
     @Test
     publicvoid createIndex() throws Exception {
         ItemsService itemsService = (ItemsService) ctx.getBean("itemsService");
         List<Items> findAll = itemsService.findAll();
         List<Document> documents = new ArrayList<Document>();
         for (Items item : findAll) {
              Document document = new Document();
              Field idField = new TextField("id", item.getId().toString(),
                       Store.YES);
              Field nameField = new TextField("name", item.getName(), Store.YES);
              Field priceField = new TextField("price", item.getPrice()
                       .toString(), Store.YES);
              Field descrptionField = new TextField("description",
                       item.getDetail(), Store.YES);
              document.add(idField);
              document.add(nameField);
              document.add(priceField);
              document.add(descrptionField);
              documents.add(document);
         }
         // 创建分词器
         IKAnalyzer ikAnalyzer = new IKAnalyzer();
 
         // 创建索引配置
         IndexWriterConfig cfg = new IndexWriterConfig(Version.LUCENE\_4\_10\_3,
                   ikAnalyzer);
 
         // 指定索引库地址
         File indexFile = new File("F:\\\\lucene\\\\index");
         Directory directory = FSDirectory.open(indexFile);
         IndexWriter indexWriter = new IndexWriter(directory, cfg);
         // 通过IndexWriter对象将Document写入到索引库中
         for (Document document : documents) {
              indexWriter.addDocument(document);
         }
         indexWriter.close();
     }
 
     /\*\*
      \* 删除索引
      \*
      \* @throws IOException
      \*/
     @Test
     publicvoid testDeleteIndex() throws IOException {
         // 1、指定索引库目录
         Directory directory = FSDirectory.open(new File("F:\\\\lucene\\\\index"));
         // 创建分词器
         IKAnalyzer ikAnalyzer = new IKAnalyzer();
         // 2、创建IndexWriterConfig
         IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE\_4\_10\_3,
                   ikAnalyzer);
         // 3、创建IndexWriter
         IndexWriter indexWriter = new IndexWriter(directory, config);
         // 4、通过IndexWriter来删除索引
         indexWriter.deleteDocuments(new Term("id", "1"));
         // 测试全部删除
         // indexWriter.deleteAll();
         indexWriter.close();
     }
 
     /\*\*
      \* 更新索引
      \*
      \* @throws Exception
      \*/
     @Test
     publicvoid updateIndex() throws Exception {
         Directory directory = FSDirectory.open(new File("F:\\\\lucene\\\\index"));
         IndexWriterConfig arg1 = new IndexWriterConfig(Version.LUCENE\_4\_10\_3,
                   new IKAnalyzer());
         IndexWriter indexWriter = new IndexWriter(directory, arg1);
         Document document = new Document();
         document.add(new TextField("name", "java", Store.YES));
         /\*\*
          \* 参数1:指定更新条件,id为1的更新为新文档对象参数2:修改后的文档对象更新流程:查询:有索引>删索引>增索引>覆盖新的文档对象无
          \* 索引>增索引
          \*/
         indexWriter.updateDocument(new Term("name", "javascript"), document);
     }
 
     /\*\*
      \* 搜索
      \*
      \* @throws ParseException
      \* @throws Exception
      \*/
     @Test
     publicvoid search() throws ParseException, Exception {
         // 创建query对象
         // 使用QueryParser搜索时,需要指定分词器,搜索时的分词器要和索引时的分词器一致
         // 第一个参数:默认搜索的域的名称
         QueryParser queryParser = new QueryParser("name", new IKAnalyzer());
 
         // 通过queryparser来创建query对象
         // 参数:输入的lucene的查询语句(关键字一定要大写)
         Query query = queryParser.parse("name:java OR lucene");
 
         // 创建IndexSearcher
         // 指定索引库的地址
         File path = new File("F:\\\\lucene\\\\index");
         Directory directory = FSDirectory.open(path);
         IndexReader r = DirectoryReader.open(directory);
         IndexSearcher indexSearcher = new IndexSearcher(r);
         // 通过searcher来搜索索引库
         // 第二个参数:指定需要显示的顶部记录的N条
         TopDocs topDocs = indexSearcher.search(query, 20);
         // 根据查询条件匹配出的记录总数
         System.out.println(topDocs.totalHits);
 
         // 根据查询条件匹配出的记录
         ScoreDoc\[\] scoreDocs = topDocs.scoreDocs;
         for (ScoreDoc scoreDoc : scoreDocs) {
              int scoreDocId = scoreDoc.doc;// 获得id
              Document doc = indexSearcher.doc(scoreDocId);
              System.out.println("商品ID:" + doc.get("id"));
              System.out.println("商品名称:" + doc.get("name"));
              System.out.println("商品价格:" + doc.get("price"));
              System.out.println("商品图片地址:" + doc.get("pic"));
         }
         r.close();
     }
 
     privatevoid search(Query query) throws Exception {
         File path = new File("F:\\\\lucene\\\\index");
         Directory directory = FSDirectory.open(path);
         IndexReader r = DirectoryReader.open(directory);
         IndexSearcher indexSearcher = new IndexSearcher(r);
         TopDocs topDocs = indexSearcher.search(query, 10);
         ScoreDoc\[\] scoreDocs = topDocs.scoreDocs;
         for (ScoreDoc sDoc : scoreDocs) {
              int docid = sDoc.doc;
              Document doc = indexSearcher.doc(docid);
              System.out.println("商品ID:" + doc.get("id"));
              System.out.println("商品名称:" + doc.get("name"));
              System.out.println("商品价格:" + doc.get("price"));
              System.out.println("商品图片地址:" + doc.get("pic"));
         }
     }
 
     @Test
     // 通过query 子类 TermQuery
     publicvoid query1() throws Exception {
         TermQuery query = new TermQuery(new Term("name", "java"));
         search(query);
     }
 
     @Test
     // 通过query 子类NumericRangeQuery
     publicvoid query2() throws Exception {
         /\*\*
          \* 参数 1、域名称 2、最小值 3、最大值 4、是否包含最小值 5、是否包含最大值
          \*/
         Query query = NumericRangeQuery.newFloatRange("price", 55f, 100f, true,
                   true);
         search(query);
     }
 
     @Test
     // 通过query 子类组合查询 BooleanQuery
     publicvoid query3() throws Exception {
         TermQuery query1 = new TermQuery(new Term("name", "java"));
         Query query2 = NumericRangeQuery.newFloatRange("price", 55f, 100f,
                   true, true);
         BooleanQuery query = new BooleanQuery();
         // MUST:查询条件必须满足,相当于AND
         // SHOULD:查询条件可选,相当于OR
         // MUST\_NOT:查询条件不能满足,相当于NOT非
         query.add(query1, Occur.MUST);
         query.add(query2, Occur.MUST\_NOT);
         search(query);
     }
 
     @Test
     // 7.3.2 MultiFieldQueryParser
     publicvoid query4() throws Exception {
         String\[\] fields = { "name", "desc" };
         MultiFieldQueryParser multiFieldQueryParser = new MultiFieldQueryParser(
                   fields, new IKAnalyzer());
         Query query = multiFieldQueryParser.parse("java");
         search(query);
     }
 
     @Test
      // 设置boot 进行排序(创建索引时指定boot值,搜索时制定boot值)
     publicvoid query5() throws Exception {
         String\[\] fields = { "name", "desc" };
         Map<String, Float> boot = new HashMap<String, Float>();
         boot.put("name", 200f);
         MultiFieldQueryParser multiFieldQueryParser = new MultiFieldQueryParser(
                   fields, new IKAnalyzer(), boot);
         Query query = multiFieldQueryParser.parse("java");
         search(query);
     }
    
}

原文链接 https://www.hanyuanhun.cn | https://node.hanyuanhun.cn

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值