top.sj.lucene.LuceneSearchUtil.java Source code

Java tutorial

Introduction

Here is the source code for top.sj.lucene.LuceneSearchUtil.java

Source

/*
 * Project Name: SJBlog
 * Class Name: LuceneSearchUtil.java
 * 
 * Copyright  2011-2016 SteveJrong  All Rights Reserved.
 * 
 * Licensed under the SteveJrong
 * 
 * https://www.steve.jrong.top/
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package top.sj.lucene;

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

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Formatter;
import org.apache.lucene.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.SimpleSpanFragmenter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import top.sj.dto.LuceneSearchDTO;
import top.sj.tool.PropertiesTool;

/**
 * Apache Lucene?
 * 
 * Create User: SteveJrong
 * Create Date: 2016611 ?5:21:54
 * Modify User: SteveJrong
 * Modify Date: 2016611 ?5:21:54
 * Modify Remark: 
 * 
 * @author SteveJrong
 * @version 1.0
 */
public class LuceneSearchUtil {

    /**
     * ?
     */
    private static Integer MAX_SEARCH_RESULT = Integer.MAX_VALUE;

    /**
     * ???
     * 
     * @param primaryKeyByHibernateEntity
     *            Hibernate??
     * @param analysisTarget
     *            ?????
     * @param analysisCondition
     *            ????
     * @return ????
     * @throws IOException
     * @throws ParseException
     * @throws InvalidTokenOffsetsException
     */
    public static List<LuceneSearchDTO> searchOfSingleAreaAndSingleCondition(String primaryKeyByHibernateEntity,
            String analysisTarget, String analysisCondition)
            throws IOException, ParseException, InvalidTokenOffsetsException {

        String configPath = PropertiesTool.getPropertiesFileAsObject("lucene_config.properties")
                .getProperty("index_location");
        Directory dir = null;
        try {
            dir = FSDirectory.open(new File(configPath));
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Directory dir = FSDirectory.open(new File("D:\\lucene"));

        IndexSearcher searcher = new IndexSearcher(dir);

        QueryParser parser = new QueryParser(Version.LUCENE_30, analysisTarget,
                new StandardAnalyzer(Version.LUCENE_30));

        // ??
        Query query = parser.parse(analysisCondition);

        TopDocs topDocs = searcher.search(query, MAX_SEARCH_RESULT);

        /**
         * 
         */
        QueryScorer queryScorer = new QueryScorer(query);
        Fragmenter fragmenter = new SimpleSpanFragmenter(queryScorer);
        Formatter formatter = new SimpleHTMLFormatter("<b>", "<b/>");
        Highlighter highlighter = new Highlighter(formatter, queryScorer);
        highlighter.setTextFragmenter(fragmenter);

        List<LuceneSearchDTO> analysisResults = new ArrayList<LuceneSearchDTO>();

        for (int i = 0; i < topDocs.scoreDocs.length; i++) {
            int docId = topDocs.scoreDocs[i].doc;
            Document doc = searcher.doc(docId);
            String attr = highlighter.getBestFragment(new StandardAnalyzer(Version.LUCENE_30), analysisTarget,
                    doc.get(analysisTarget));
            analysisResults.add(new LuceneSearchDTO(Integer.valueOf(doc.get(primaryKeyByHibernateEntity)), attr));
        }
        return analysisResults;
    }

    /**
     * ??
     * 
     * @param primaryKeyByHibernateEntity
     *            Hibernate??
     * @param analysisTarget
     *            ?????
     * @param analysisConditions
     *            ?????????????
     * @return ????
     * @throws IOException
     * @throws ParseException
     * @throws InvalidTokenOffsetsException
     */
    public static List<LuceneSearchDTO> searchOfSingleAreaAndMultiCondition(String primaryKeyByHibernateEntity,
            String analysisTarget, String... analysisConditions)
            throws IOException, ParseException, InvalidTokenOffsetsException {
        String configPath = PropertiesTool.getPropertiesFileAsObject("lucene_config.properties")
                .getProperty("index_location");
        Directory dir = FSDirectory.open(new File(configPath));

        // Directory dir = FSDirectory.open(new File("D://lucene"));
        IndexSearcher searcher = new IndexSearcher(dir);

        QueryParser parser = new QueryParser(Version.LUCENE_30, analysisTarget,
                new StandardAnalyzer(Version.LUCENE_30));

        BooleanQuery query = new BooleanQuery();

        for (int i = 0; i < analysisConditions.length; i++) {
            Query query1 = parser.parse(analysisConditions[i]);
            query.add(query1, i == 0 ? Occur.MUST : Occur.SHOULD);
        }
        TopDocs topDocs = searcher.search(query, MAX_SEARCH_RESULT);

        /**
         * 
         */
        QueryScorer queryScorer = new QueryScorer(query);
        Fragmenter fragmenter = new SimpleSpanFragmenter(queryScorer);
        Formatter formatter = new SimpleHTMLFormatter("<b>", "<b/>");
        Highlighter highlighter = new Highlighter(formatter, queryScorer);
        highlighter.setTextFragmenter(fragmenter);

        List<LuceneSearchDTO> analysisResults = new ArrayList<LuceneSearchDTO>();

        for (int i = 0; i < topDocs.scoreDocs.length; i++) {
            int docId = topDocs.scoreDocs[i].doc;
            Document doc = searcher.doc(docId);
            String attr = highlighter.getBestFragment(new StandardAnalyzer(Version.LUCENE_30), analysisTarget,
                    doc.get(analysisTarget));
            analysisResults.add(new LuceneSearchDTO(Integer.valueOf(doc.get(primaryKeyByHibernateEntity)), attr));
        }
        return analysisResults;
    }
}