SearchLuceneForCmsLog

package com.yulong.lucene.biz;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
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.queryParser.MultiFieldQueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MultiSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.util.Version;

import com.yulong.lucene.core.LuceneContacts;
import com.yulong.lucene.util.LabelUtil;
import com.yulong.lucene.util.RequestUtil;
import com.yulong.model.Goods;
import com.yulong.util.StringUtil;

/**
* 后台多并发搜索文章处理日志
*
* @author fyh
*
*/
public class SearchLuceneForCmsLog
{
   
    /**
     * LOG.
     */
    private static final Logger LOG = Logger.getLogger(SearchLuceneForCmsLog.class);
    private static String LS = "<font color='red'><b>";
    private static String LE = "</b></font>";
   
    /**
     * 后台内容管理处,信息检索
     *
     * @param keyword 搜索关键字
     * @param start 记录开始
     * @param max 记录结束
     * @param orderByField 排序字段
     * @param orderByType 排序类型(asc:升序,其他:降序)
     *
     * @throws IOException
     */
    @SuppressWarnings({ "unchecked", "deprecation" })
    public static String SearchForContent2(String keyword, int start, int max, String orderByField, String orderByType)
            throws Exception
    {
   
        // 可检索索引
        String path = "X:/index/" + "/index";
        IndexSearcher indexSearcher = new IndexSearcher(path);
        IndexSearcher indexSearchers[] = { indexSearcher };
        MultiSearcher searcher = new MultiSearcher(indexSearchers);
        String str = "";
        if (searcher != null)
        {
            // 开始搜索
            // 查询字段
            String[] fields = { "saleName", "name", "advertiseWords" };
            BooleanClause.Occur[] clauses = { BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD,
                                             BooleanClause.Occur.SHOULD };
            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
            Query query = MultiFieldQueryParser.parse(keyword, fields, clauses, analyzer);
            // 排序
            boolean orderby = true;
            if ("asc".equalsIgnoreCase(orderByType))
            {
                orderby = false;
            }
            SortField sortField = new SortField(orderByField, orderby);
            Sort sort = new Sort(sortField);
            Hits top = searcher.search(query, sort);
            if (max > top.length())
                max = top.length();
            // 处理结果集
            for (int i = start; i < max; i++)
            {
                Document doc = top.doc(i);
                if (str != "")
                    str += ",";
                List<Field> list = doc.getFields();
                String temp = "";
                for (Field d : list)
                {
                    if ("goodsId".equals(d.name()))
                    {
                        // 获取图片ID,根据goodsId获取图片.
                        String goodsId = RequestUtil.VailStr(d.stringValue(), "");
                        System.out.println("开始获取ID=" + goodsId + "的图片...");
                        // .......................未实现.
                    }
                    if (temp != "")
                        temp += ",";
                    temp += "\"" + d.name() + "\":\"" + LabelUtil.filter(RequestUtil.VailStr(d.stringValue(), ""))
                            + "\"";
                }
                str += "{" + temp + "}";
            }
            searcher.close();
        }
        // str = "{\"data\":[" + str + "],\"total\":\"" + num + "\"}";
        return str;
    }
   
    /**
     * 后台内容管理处,信息检索
     *
     * @param keyword 搜索关键字
     * @param start 记录开始
     * @param max 记录结束
     * @param orderByField 排序字段
     * @param orderByType 排序类型(asc:升序,其他:降序)
     *
     * @throws IOException
     */
    @SuppressWarnings({ "unchecked", "deprecation" })
    public static List<Goods> SearchForContent(String indexPath, String keyword, int start, int max,
            String orderByField, String orderByType) throws Exception
    {
   
        List<Goods> goodsList = new ArrayList<Goods>();
        String path = indexPath + "index";
        IndexSearcher indexSearcher = new IndexSearcher(path);
        IndexSearcher indexSearchers[] = { indexSearcher };
        MultiSearcher searcher = new MultiSearcher(indexSearchers);
        if (searcher != null)
        {
            String[] fields = { "saleName", "advertiseWords" };
            BooleanClause.Occur[] clauses = { BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD };
            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
            keyword = LabelUtil.filter(keyword);
            Query query = MultiFieldQueryParser.parse(keyword, fields, clauses, analyzer);
            boolean orderby = true;
            if ("asc".equalsIgnoreCase(orderByType))
            {
                orderby = false;
            }
            SortField sortField = new SortField(orderByField, orderby);
            Sort sort = new Sort(sortField);
            Hits top = null;
            if ("sales".equals(orderByField))
            {
                top = searcher.search(query);
            }
            else
            {
                top = searcher.search(query, sort);
            }
            SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter(LS, LE);
            Highlighter highlighter = new Highlighter(simpleHTMLFormatter, new QueryScorer(query));
            highlighter.setTextFragmenter(new SimpleFragmenter(100));
            if (max > top.length())
                max = top.length();
            for (int i = start; i < max; i++)
            {
                Document doc = top.doc(i);
                List<Field> list = doc.getFields();
                Goods good = new Goods();
                for (Field d : list)
                {
                    String filedName = d.name();
                    String value = d.stringValue();
                    if ("goodsId".equals(filedName))
                    {
                        String goodsId = RequestUtil.VailStr(value, "");
                        good.setGoods_id(Long.parseLong(goodsId));
                    }
                    if ("saleName".equals(filedName))
                    {
                        String filterStr = LabelUtil.filter(RequestUtil.VailStr(d.stringValue(), ""));
                        String highliStr = highlighter.getBestFragment(LuceneContacts.analyzer, d.name(), filterStr);
                        if (StringUtil.isEmpty(highliStr))
                        {
                            good.setSale_name(RequestUtil.VailStr(value, ""));
                        }
                        else
                        {
                            good.setSale_name(highliStr);
                        }
                    }
                    if ("name".equals(filedName))
                    {
                        good.setName(RequestUtil.VailStr(value, ""));
                    }
                    if ("advertiseWords".equals(filedName))
                    {
                        String filterStr = LabelUtil.filter(RequestUtil.VailStr(d.stringValue(), ""));
                        String highliStr = highlighter.getBestFragment(LuceneContacts.analyzer, d.name(), filterStr);
                        if (StringUtil.isEmpty(highliStr))
                        {
                            good.setAdvertise_words(RequestUtil.VailStr(value, ""));
                        }
                        else
                        {
                            good.setAdvertise_words(highliStr);
                        }
                    }
                    if ("price".equals(filedName))
                    {
                        if (value != null && !"".equals(value) && !"null".equals(value))
                        {
                            good.setPrice(new BigDecimal(value));
                        }
                        else
                        {
                            good.setPrice(new BigDecimal(0));
                        }
                    }
                    if ("onShelfTime".equals(filedName))
                    {
                        Date date = null;
                        if (value != null && !"".equals(value))
                        {
                            date = new Date(RequestUtil.FormatDaeHH(value));
                        }
                        good.setOn_shelf_time(date);
                    }
                    if ("primaryPicName".equals(filedName))
                    {
                        good.setPrimaryPicName(RequestUtil.VailStr(value, ""));
                    }
                    if ("imgPath".equals(filedName))
                    {
                        good.setImgPath(RequestUtil.VailStr(value, ""));
                    }
                    if ("picType".equals(filedName))
                    {
                        good.setPicType(RequestUtil.VailStr(value, ""));
                    }
                }
                goodsList.add(good);
            }
            searcher.close();
        }
        return goodsList;
    }
   
    /**
     * 后台内容管理处,信息检索
     *
     * @param keyword 搜索关键字
     * @param start 记录开始
     * @param max 记录结束
     * @param orderByField 排序字段
     * @param orderByType 排序类型(asc:升序,其他:降序)
     *
     * @throws IOException
     */
    @SuppressWarnings("deprecation")
    public static int getTotalIndex(String indexPath, String keyword, String orderByField, String orderByType)
            throws Exception
    {
   
        String path = indexPath + "index";
        IndexSearcher indexSearcher = new IndexSearcher(path);
        IndexSearcher indexSearchers[] = { indexSearcher };
        MultiSearcher searcher = new MultiSearcher(indexSearchers);
        int num = 0;
        if (searcher != null)
        {
            String[] fields = { "saleName", "advertiseWords" };
            BooleanClause.Occur[] clauses = { BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD };
            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
            keyword = LabelUtil.filter(keyword);
            Query query = MultiFieldQueryParser.parse(keyword, fields, clauses, analyzer);
           
            Hits top = searcher.search(query);
            num = top.length();
            searcher.close();
        }
        return num;
    }
}

你可能感兴趣的:(Lucene)