lucene 入门(代码已经过测试)

1、所需jar


    lucene-analyzers-common-4.7.0.jar
    lucene-core-4.7.0.jar
    lucene-queries-4.7.0.jar
    lucene-queryparser-4.7.0.jar

 

2、代码  已测试。

     将测试表的数据假如索引,然后进行搜索查询

 

package com.jh.lencene;

import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.Date;
import java.util.List;

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.document.Field.TermVector;
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.IndexWriterConfig.OpenMode;
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.Filter;
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.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.jh.pojo.User;

public class HelloLucene {
 public static void main(String[] args) throws IOException, ParseException {
  /*Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
  // Store the index in memory:
  Directory directory = new RAMDirectory();
  // To store an index on disk, use this instead:
  // Directory directory = FSDirectory.open(new File("H:/luceneIndex"));
  IndexWriterConfig config = new IndexWriterConfig(
    Version.LUCENE_CURRENT, analyzer);
  IndexWriter iwriter = new IndexWriter(directory, config);
  Document doc = new Document();
  String text = "This is the text to be indexed.";
  doc.add(new Field("fieldname", text, TextField.TYPE_STORED));
  iwriter.addDocument(doc);
  iwriter.close();
  System.out.println("建立索引 ok");

  // Now search the index:
  DirectoryReader ireader = DirectoryReader.open(directory);
  IndexSearcher isearcher = new IndexSearcher(ireader);
  // Parse a simple query that searches for "text":
  QueryParser parser = new QueryParser(Version.LUCENE_CURRENT,
    "fieldname", analyzer);
  Query query = parser.parse("text");
  ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
  System.out.println(hits.length == 1);
  // Iterate through the results:
  for (int i = 0; i < hits.length; i++) {
   Document hitDoc = isearcher.doc(hits[i].doc);
   System.out.println(hitDoc.get("fieldname"));
  }
  ireader.close();
  directory.close();*/

  try {
   //new HelloLucene().createSearch();
   //new HelloLucene().searchKeyword("xx");

   new HelloLucene().search("a*");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }


 /**
  * 创建索引
  */
 public String createSearch() throws Exception {
  System.out.println("开始创建索引。。。");
  long stime = new Date().getTime();
  Directory dir = FSDirectory.open(new File("E:\\test"));
  Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
  IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36,
    analyzer);
  iwc.setOpenMode(OpenMode.CREATE); //即创建新索引文件OpenMode.CREATE_OR_APPEND表示创建或追加到已有索引文件
  IndexWriter writer = new IndexWriter(dir, iwc);

  SessionFactory sessionFactory = new Configuration().configure()
    .buildSessionFactory();
  Session session = sessionFactory.openSession();

  //需要建立 索引的数据
  List<User> users = session.createSQLQuery(" select * from user2")
    .addEntity(User.class).list();

  for (User u : users) {
   Document doc = new Document();
   System.out.println(u.getName());
   // int 要转换 String
   doc.add(new Field("id", String.valueOf(u.getId()), Field.Store.YES,
     Field.Index.ANALYZED));
   doc.add(new Field("name", u.getName(), Field.Store.YES,
     Field.Index.ANALYZED));

   writer.addDocument(doc);
  }
  writer.forceMerge(1);
  writer.close();
  long endTime = new Date().getTime();
  System.out.println("这花费了 " + (endTime - stime) + "毫秒来把数据增加到索引里面去!");
  return "succ";
 }

 public void search(String queryStr) throws Exception {
  long startTime = new Date().getTime();
  String[] fields = { "name", "content" };//第一个字段用来指定索引的字段
  Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_47);
  QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_47,
    fields, analyzer);
  Query query = null;
  Filter filter = null;
  query = queryParser.parse(queryStr);
  IndexReader reader = IndexReader.open(FSDirectory.open(new File(
    "E:\\test")));
  IndexSearcher indexSearcher = new IndexSearcher(reader);
  IndexSearcher searcher = new IndexSearcher(reader);
  TopDocs topDocs = indexSearcher.search(query, filter, 1000);

  ScoreDoc[] hits = topDocs.scoreDocs;

  System.out.println("hits.length = " + hits.length);


  Document doc = null;
  for (ScoreDoc scorceDoc : hits) {
   doc = searcher.doc(scorceDoc.doc);
   System.out.println(queryStr + " = key .... " + doc.get("id") + "=id  ...  name = " + doc.get("name"));
  }
  System.out.println("总共有" + topDocs.totalHits + "条记录:");
  /* for (ScoreDoc scoreDoc : topDocs.scoreDocs) { 
       int docNum = scoreDoc.doc; 
       Document doc = indexSearcher.doc(docNum); 
       File2DocumentUtil.printDocumentInfo(doc); 
   } */
 }
}

 

 

测试结果:

hits.length = 5
a* = key .... 00002=id  ...  name = admin2
a* = key .... bfe7fa941c8841ec8ede01d3f1adbe79=id  ...  name = ass
a* = key .... 0d6c96db117e4039a00df646b8323112=id  ...  name = ass2
a* = key .... e719297fdb364735b6e1fd4f55723ead=id  ...  name = aaaa
a* = key .... 00001=id  ...  name = admin1
总共有5条记录:

你可能感兴趣的:(Lucene)