org.bidtime.lucene.index.LuceneIndexAndSearchDemo.java Source code

Java tutorial

Introduction

Here is the source code for org.bidtime.lucene.index.LuceneIndexAndSearchDemo.java

Source

/**
 * IK ?   5.0
 * IK Analyzer release 5.0
 * 
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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.
 *
 * ??(linliangyi2005@gmail.com)??
 * ? 2012
 * provided by Linliangyi and copyright 2012 by Oolong studio
 * 
 * 
 */
package org.bidtime.lucene.index;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.CorruptIndexException;
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.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
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.LockObtainFailedException;
import org.apache.lucene.store.RAMDirectory;
import org.wltea4pinyin.analyzer.lucene.IKAnalyzer4PinYin;

/**
 * IKAnalyzerLucene
 * 2012-3-2
 * 
 * ?Lucene4.0 API
 *
 */
public class LuceneIndexAndSearchDemo {

    /**
     * 
     * ???
     * @param args
     */
    public static void main(String[] args) {
        //Lucene Document??
        String fieldName = "hanzi";
        String quanpin = "pinyin";
        String shouzimu = "shouzimu";
        //
        String text = "IK Analyzer???????";

        //IKAnalyzer?
        //PerFieldAnalyzerWrapper???field???
        Map<String, Analyzer> analyzerMap = new HashMap<String, Analyzer>();
        analyzerMap.put(quanpin, new IKAnalyzer4PinYin(false, IKAnalyzer4PinYin.PINYIN));
        analyzerMap.put(shouzimu, new IKAnalyzer4PinYin(false, IKAnalyzer4PinYin.PINYIN_SHOUZIMU));
        PerFieldAnalyzerWrapper wrapper = new PerFieldAnalyzerWrapper(new IKAnalyzer4PinYin(false), analyzerMap);

        Directory directory = null;
        IndexWriter iwriter = null;
        IndexReader ireader = null;
        IndexSearcher isearcher = null;
        try {
            //
            directory = new RAMDirectory();

            //?IndexWriterConfig
            IndexWriterConfig iwConfig = new IndexWriterConfig(wrapper);
            iwConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
            iwriter = new IndexWriter(directory, iwConfig);
            //
            Document doc = new Document();
            doc.add(new StringField("ID", "10000", Field.Store.YES));
            doc.add(new TextField(fieldName, text, Field.Store.YES));
            doc.add(new TextField(quanpin, text, Field.Store.YES));
            doc.add(new TextField(shouzimu, text, Field.Store.YES));

            iwriter.addDocument(doc);
            iwriter.close();

            //?**********************************
            //?   
            ireader = DirectoryReader.open(directory);
            isearcher = new IndexSearcher(ireader);

            String keyword = "";
            //QueryParser?Query
            Analyzer analyzer = new IKAnalyzer4PinYin(true);
            QueryParser qp = new QueryParser(fieldName, analyzer);
            QueryParser qpQuanpin = new QueryParser(quanpin, analyzer);
            QueryParser qpShouzimu = new QueryParser(shouzimu, analyzer);

            Query query = qp.parse(keyword);
            Query queryQuanpin = qpQuanpin.parse(keyword);
            Query queryShouzimu = qpShouzimu.parse(keyword);
            //            
            BooleanQuery bq = new BooleanQuery();
            BooleanQuery innerbq = new BooleanQuery();
            //            
            bq.add(query, BooleanClause.Occur.SHOULD);
            bq.add(queryQuanpin, BooleanClause.Occur.SHOULD);
            bq.add(queryShouzimu, BooleanClause.Occur.SHOULD);
            innerbq.add(bq, BooleanClause.Occur.MUST);

            //         System.out.println("innerbq = " + innerbq);

            //?5?
            TopDocs topDocs = isearcher.search(innerbq, 5);
            System.out.println("" + topDocs.totalHits);
            //
            ScoreDoc[] scoreDocs = topDocs.scoreDocs;
            for (int i = 0; i < topDocs.totalHits; i++) {
                Document targetDoc = isearcher.doc(scoreDocs[i].doc);
                System.out.println("" + targetDoc.toString());
            }

        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (LockObtainFailedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
            if (ireader != null) {
                try {
                    ireader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (directory != null) {
                try {
                    directory.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}