[java] 아파치 루신(Apache Lucene)을 이용한 태깅 및 주석 처리 구현 방법

아파치 루신은 자바 기반의 오픈소스 검색 엔진 라이브러리로, 텍스트 데이터의 태깅 및 주석 처리를 구현하는데 많이 사용됩니다. 이번 포스트에서는 아파치 루신을 이용하여 텍스트 데이터에 태그를 추가하고 주석을 달아주는 방법을 알아보겠습니다.

1. 아파치 루신 추가하기

아파치 루신을 사용하기 위해서는 먼저 프로젝트에 아파치 루신 라이브러리를 추가해야 합니다. Maven을 사용하는 경우, pom.xml 파일에 다음 의존성을 추가합니다:

<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-core</artifactId>
    <version>8.8.1</version>
</dependency>

Gradle을 사용하는 경우, build.gradle 파일에 다음 의존성을 추가합니다:

dependencies {
    implementation 'org.apache.lucene:lucene-core:8.8.1'
}

의존성을 추가한 후에는 프로젝트를 다시 빌드해야 합니다.

2. 태깅 처리 구현하기

먼저, 태깅을 처리하기 위해 TaggingProcessor 클래스를 만들어 보겠습니다. 이 클래스는 텍스트 데이터를 입력으로 받아 해당 텍스트에 태그를 추가하는 역할을 합니다. 다음은 TaggingProcessor의 예시 코드입니다.

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class TaggingProcessor {
    private Analyzer analyzer;
    private Directory indexDir;
    private IndexWriterConfig config;

    public TaggingProcessor(String indexPath) throws IOException {
        this.analyzer = new StandardAnalyzer();
        Path path = Paths.get(indexPath);
        this.indexDir = FSDirectory.open(path);
        this.config = new IndexWriterConfig(analyzer);
    }

    public void tagText(String inputText, String tag) throws IOException {
        IndexWriter writer = new IndexWriter(indexDir, config);
        Document doc = new Document();
        doc.add(new TextField("content", inputText, Field.Store.YES));
        doc.add(new StringField("tag", tag, Field.Store.YES));
        writer.addDocument(doc);
        writer.close();
    }
}

TaggingProcessor 클래스는 tagText 메소드를 제공합니다. 이 메소드는 먼저 입력된 텍스트(inputText)와 해당 텍스트에 추가할 태그(tag)를 받아옵니다. 그런 후, IndexWriter를 사용하여 텍스트와 태그를 포함한 Document를 만들고, 이를 인덱스에 추가합니다.

3. 주석 처리 구현하기

주석 처리를 위해 AnnotationProcessor 클래스를 만들어 보겠습니다. 이 클래스는 특정 텍스트에 대한 주석을 저장하고, 저장된 주석을 검색하는 역할을 합니다. 다음은 AnnotationProcessor의 예시 코드입니다.

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class AnnotationProcessor {
    private Analyzer analyzer;
    private Directory indexDir;
    private IndexReader reader;

    public AnnotationProcessor(String indexPath) throws IOException {
        this.analyzer = new StandardAnalyzer();
        Path path = Paths.get(indexPath);
        this.indexDir = FSDirectory.open(path);
        this.reader = DirectoryReader.open(indexDir);
    }

    public void addAnnotation(String text, String annotation) throws IOException {
        IndexWriterConfig config = new IndexWriterConfig(analyzer);
        IndexWriter writer = new IndexWriter(indexDir, config);

        Document doc = new Document();
        doc.add(new TextField("content", text, Field.Store.YES));
        doc.add(new TextField("annotation", annotation, Field.Store.YES));

        writer.addDocument(doc);
        writer.close();
    }

    public List<String> searchAnnotations(String keyword) throws IOException {
        IndexSearcher searcher = new IndexSearcher(reader);
        QueryParser parser = new QueryParser("annotation", analyzer);
        Query query;
        try {
            query = parser.parse(keyword);
        } catch (org.apache.lucene.queryparser.classic.ParseException e) {
            throw new IOException("Failed to parse query: " + keyword, e);
        }
        TopDocs results = searcher.search(query, 10);
        List<String> annotations = new ArrayList<>();
        for (ScoreDoc scoreDoc : results.scoreDocs) {
            Document doc = searcher.doc(scoreDoc.doc);
            annotations.add(doc.getField("annotation").stringValue());
        }
        return annotations;
    }
}

AnnotationProcessor 클래스는 addAnnotation 메소드와 searchAnnotations 메소드를 제공합니다. addAnnotation 메소드는 입력된 텍스트에 대한 주석(annotation)을 인덱스에 추가합니다. searchAnnotations 메소드는 특정 키워드(keyword)에 대한 주석을 검색하여 리스트로 반환합니다.

4. 사용 예시

이제 TaggingProcessorAnnotationProcessor 클래스를 사용하여 태깅 및 주석 처리를 구현해보겠습니다. 다음은 예시 코드입니다.

public class Main {
    public static void main(String[] args) {
        try {
            // 태깅 처리
            TaggingProcessor taggingProcessor = new TaggingProcessor("index/tagging");
            taggingProcessor.tagText("This is a sample text.", "sample");

            // 주석 처리
            AnnotationProcessor annotationProcessor = new AnnotationProcessor("index/annotation");
            annotationProcessor.addAnnotation("This is the first sentence.", "This sentence is important.");

            // 주석 검색
            List<String> annotations = annotationProcessor.searchAnnotations("important");
            for (String annotation : annotations) {
                System.out.println(annotation);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 예시 코드에서는 TaggingProcessor를 사용하여 텍스트에 태그를 추가하고, AnnotationProcessor를 사용하여 특정 텍스트에 대한 주석을 저장하고 검색합니다.

결론

아파치 루신을 사용하여 텍스트 데이터의 태깅 및 주석 처리를 구현하는 방법을 알아보았습니다. 이를 통해 텍스트 데이터의 태그 추가와 주석 검색 기능을 쉽게 구현할 수 있습니다. 루신은 많은 기능과 유연성을 제공하므로, 다양한 텍스트 처리 작업에 유용하게 사용될 수 있습니다.

참고자료