com.vnet.demo.service.lucene.LuceneService.java Source code

Java tutorial

Introduction

Here is the source code for com.vnet.demo.service.lucene.LuceneService.java

Source

/*
 * Copyright (c) 2015-2020, Chen Rui
 *
 * Licensed 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.
 */

package com.vnet.demo.service.lucene;

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.document.Field;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
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 org.apache.lucene.store.Directory;
import org.apache.lucene.util.Version;

import com.vnet.demo.utils.IOUtils;

public class LuceneService {

    private StandardAnalyzer analyzer;

    private Directory index;

    private Version version;

    public LuceneService(StandardAnalyzer analyzer, Directory index, Version version) {
        this.analyzer = analyzer;
        this.index = index;
        this.version = version;
    }

    public void addDoc(DocumentData documentData) {
        IndexWriterConfig config = new IndexWriterConfig(version, analyzer);
        IndexWriter write = null;
        try {
            write = new IndexWriter(index, config);
            Document doc = new Document();
            doc.add(new LongField("id", documentData.getId(), Field.Store.YES));
            doc.add(new TextField("title", documentData.getTitle(), Field.Store.YES));
            doc.add(new TextField("summary", documentData.getSummary(), Field.Store.YES));
            doc.add(new TextField("context", documentData.getContext(), Field.Store.YES));
            doc.add(new LongField("createDate", documentData.getCreateDate(), Field.Store.YES));
            write.addDocument(doc);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(write);
        }
    }

    public void updateDoc(DocumentData documentData) {
        IndexWriterConfig config = new IndexWriterConfig(version, analyzer);
        IndexWriter write = null;
        try {
            write = new IndexWriter(index, config);
            Document doc = new Document();
            doc.add(new LongField("id", documentData.getId(), Field.Store.YES));
            doc.add(new TextField("title", documentData.getTitle(), Field.Store.YES));
            doc.add(new TextField("summary", documentData.getSummary(), Field.Store.YES));
            doc.add(new TextField("context", documentData.getContext(), Field.Store.YES));
            doc.add(new LongField("createDate", documentData.getCreateDate(), Field.Store.YES));
            write.updateDocument(new Term("id", documentData.getId().toString()), doc);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(write);
        }
    }

    public void deleteDoc(DocumentData documentData) {
        IndexWriterConfig config = new IndexWriterConfig(version, analyzer);
        IndexWriter write = null;
        try {
            write = new IndexWriter(index, config);
            write.deleteDocuments(new Term("id", documentData.getId().toString()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(write);
        }
    }

    public SearchResult<DocumentData> query(String keyword, int start, int number) {
        SearchResult<DocumentData> searchResult = null;
        try {
            List<DocumentData> documentDatas = new ArrayList<DocumentData>();
            DirectoryReader ireader = DirectoryReader.open(index);
            IndexSearcher isearcher = new IndexSearcher(ireader);
            Query query = new QueryParser(version, "title", analyzer).parse(keyword + "*");

            TopDocs hits = null;
            if (start > 0) {
                TopDocs result = isearcher.search(query, start);
                ScoreDoc scoreDoc = result.scoreDocs[result.scoreDocs.length - 1];
                hits = isearcher.searchAfter(scoreDoc, query, number);
            } else {
                hits = isearcher.search(query, number);
            }
            for (int i = 0; i < hits.scoreDocs.length; i++) {
                DocumentData data = new DocumentData();
                Document hitDoc = isearcher.doc(hits.scoreDocs[i].doc);
                data.setId(Long.parseLong(hitDoc.get("id")));
                data.setTitle(hitDoc.get("title"));
                data.setSummary(hitDoc.get("summary"));
                data.setCreateDate(Long.parseLong(hitDoc.get("createDate")));
                documentDatas.add(data);
            }
            searchResult = new SearchResult<DocumentData>(new Long(hits.totalHits), documentDatas);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return searchResult;
    }

}