lucene的增删改查

1、建立一个Article简单java类

public class Article {
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    private int id;

    private String title;

    private String author;

    private String content;

    private String link;


}

2、建立一个LuceneUtils工具类

import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
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.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
 * 假设的你几行代码可以完成某个功能,抽取成一个方法
 * 
 * 假设在某个业务逻辑层可以共用,往上抽取,
 * 
 * 假设在多个业务层可以共用,提炼成工具类。
 * 
 * 假设你的这个业务方法在多个系统需要被使用.. 发布成一个服务...
 * 
 * 
 * @author Administrator
 *
 */
public class LuceneUtils {

    private static Directory directory=null;

    private static IndexWriterConfig config=null;



    private static Version matchVersion=null;

    private static Analyzer analyzer=null;

    static{

        try {
            directory=FSDirectory.open(new File(Contants.INDEXURL));

            matchVersion=Version.LUCENE_44;

            analyzer=new StandardAnalyzer(matchVersion);

            config=new IndexWriterConfig(matchVersion, analyzer);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 
     * 
     * @return返回用于操作索引的对象...
     * @throws IOException
     */
    public static IndexWriter getIndexWriter() throws IOException{
        IndexWriter indexWriter=new IndexWriter(directory,config);
        return indexWriter;
    }
    /**
     * 
     * 返回用于读取索引的对象..
     * @return
     * @throws IOException
     */
    public static IndexSearcher getIndexSearcher() throws IOException{

        IndexReader indexReader=DirectoryReader.open(directory);

        IndexSearcher indexSearcher=new IndexSearcher(indexReader);

        return indexSearcher;

    }

    /**
     * 返回lucene 当前使用的版本信息...
     * 
     * @return
     */
    public static Version getMatchVersion() {
        return matchVersion;
    }

    /**
     * 
     * 
     * 返回lucene 使用的分词器...
     * @return
     */
    public static Analyzer getAnalyzer() {
        return analyzer;
    }

}

3、建立一个存储地址工具类Contants

public class Contants {
    public static final String INDEXURL="D://index/news";
}

4、建立一个转换类

import org.apache.lucene.document.Document;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.TextField;

import com.zhiyou.bean.Article;

/**
 * article 的转换类...
 * 
 * @author Administrator
 *
 */
public class ArticleUtils {

    /**
     * 将article 转换成document
     * 无非article 的值设置document里面去...
     * 
     * 
     * @param article
     * @return
     */
    public static Document articleToDocument(Article article){

        Document document=new Document();

        IntField idfield=new IntField("id",article.getId(),Store.YES);

        StringField authorfield=new StringField("author", article.getAuthor(), Store.YES);
        StringField urlfield=new StringField("link", article.getLink(), Store.YES);
        TextField title=new TextField("title", article.getTitle(),Store.YES);

        //设置权重值,默认为1f..
        //title.setBoost(4f);

        TextField contentfield=new TextField("content", article.getContent(),Store.YES);

        document.add(idfield);
        document.add(authorfield);

        document.add(urlfield);
        document.add(title);
        document.add(contentfield);

        return document;

    }
}

5、建立一个增删改查的实现类LuceneDao

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
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 com.zhiyou.bean.Article;
import com.zhiyou.utils.ArticleUtils;
import com.zhiyou.utils.LuceneUtils;

/**
 * 
 * 使用lucene 来操作索引库...
 * 
 * @author Administrator
 *
 */
public class LuceneDao {
    /**
     * 增删改索引都是通过indexWriter 对象来完成...
     * @throws IOException 
     * 
     * 
     */
    public void addIndex(Article article) throws IOException{
        IndexWriter indexWriter=LuceneUtils.getIndexWriter();
        Document doc=ArticleUtils.articleToDocument(article);
        indexWriter.addDocument(doc);
        indexWriter.close();
    }
    /**
     * 
     * 删除索引,根据字段对应的值进行删除...
     * 
     * @param fieldName
     * @param fieldValue
     * @throws IOException
     */
    public void delIndex(String fieldName,String fieldValue) throws IOException{
        IndexWriter indexWriter=LuceneUtils.getIndexWriter();



        Term term=new Term(fieldName, fieldValue);
        //delete from table where condition
        indexWriter.deleteDocuments(term);

        indexWriter.close();

    }


    /**
     * 
     * 先删除符合条件的记录,再创建一个符合条件的记录....
     * @param fieldName
     * @param fieldValue
     * @param article
     * @throws IOException
     */
    public void updateIndex(String fieldName,String fieldValue,Article article) throws IOException{
        IndexWriter indexWriter=LuceneUtils.getIndexWriter();
        Term term=new Term(fieldName, fieldValue);
        Document doc=ArticleUtils.articleToDocument(article);
        /**
         * 
         * 1:设置更新的条件
         * 
         * 
         * 2:设置更新的内容的对象...
         * 
         * 
         */
        indexWriter.updateDocument(term, doc);

        indexWriter.close();
    }
    /**
     * 
     *   显示第一页 的数据  0,10
     *  
     *   显示第二页 的数据  10,10
     *   
     *    显示第三页 的数据  20,10
     * @param keywords
     * @return
     * @throws Exception
     */
    public List<Article> findIndex(String keywords,int start,int rows) throws Exception{
        IndexSearcher indexSearcher=LuceneUtils.getIndexSearcher();
        //需要根据那几个字段进行检索...
        String   fields []={"title","content"};

        //title:yi  title:抑,title:症
        //第一种类型的条件..
//      Query query=new TermQuery(new Term("author","毕加索"));
        //第二种类型的条件
        QueryParser queryParser=new MultiFieldQueryParser(LuceneUtils.getMatchVersion(),fields,LuceneUtils.getAnalyzer());
        //不同的规则构造不同的子类..
        //title:keywords  ,content:keywords
        Query query=queryParser.parse(keywords);

        //这里检索的是索引目录

        //会把整个索引目录都读取一边...
        //检索符合query 前面N条记录...
        TopDocs topDocs=indexSearcher.search(query, start+rows);
        System.out.println("总记录数==total=="+topDocs.totalHits);
        ScoreDoc scoreDocs []=topDocs.scoreDocs;
        Article article=null;
        List<Article> articlelist=new ArrayList<Article>();


        //scoreDocs.length  vs(比较)   start+rows  取小值
        //在java jdk 里面提供了一个类,可以用来比较两个数字类型的值,取小值..
        int endResult=Math.min(scoreDocs.length, start+rows);

        for(int i=start;i<endResult;i++){
            //docID lucene 的索引库里面有很多的document,lucene 为每个document 定义一个编号,唯一标识.. 自增长
            int docID=scoreDocs[i].doc;
            System.out.println("编号的标识==="+docID);
            article=new Article();
            Document document=indexSearcher.doc(docID);
            article.setId(Integer.parseInt(document.get("id")));
            article.setTitle(document.get("title"));
            article.setContent(document.get("content"));
            article.setLink(document.get("link"));
            article.setAuthor(document.get("author"));
            articlelist.add(article);
        }
        return articlelist;
    }
}

6、建立一个测试类

import java.io.IOException;
import java.util.List;

import org.apache.lucene.index.Term;
import org.junit.Test;

import com.zhiyou.bean.Article;
import com.zhiyou.dao.LuceneDao;

public class JunitTest {


    private LuceneDao luceneDao=new LuceneDao();

    @Test
    public void addIndex() throws IOException{
        for(int i=32;i<=33;i++){
            Article article=new Article();
            article.setId(i);
            article.setTitle("solr 是基于lucene 的一个全文检索服务器.");
            article.setContent("有人问毕加索:你的画我看不懂,毕加索:鸟叫声好听,好听,听得懂吗,不懂");
            article.setAuthor("爱新觉罗杜小文");
            article.setLink("www.itheima.com");
            luceneDao.addIndex(article);
        }

    }

    @Test
    public void testDel() throws IOException{
        luceneDao.delIndex("title", "抑");

    }


    @Test
    public void testUpdate() throws IOException{

       String fieldName="title";

       String fieldValue="抑";

       Article article=new Article();


       article.setId(9527);

       article.setAuthor("王昭厅");


       article.setTitle("你厅歌很黄");

       article.setContent("你厅歌今天用的是黑妹洗发水");

       article.setLink("http://www.itheima.com");


       luceneDao.updateIndex(fieldName, fieldValue, article);

    }


    @Test
    public void testsearcher() throws Exception{
        String keywords="抑郁症";
        //title content   textfield 现在使用的分词器是单字分词..
        //title:有
        //title:
        //author:毕加索
        List<Article> listArticles=luceneDao.findIndex(keywords,0,10);
        for(Article article:listArticles){
            System.out.println(article.getId());
            System.out.println(article.getAuthor());
            System.out.println(article.getLink());
            System.out.println(article.getContent());
            System.out.println(article.getTitle());

        }
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值