구문 쿼리는 특정 용어 시퀀스가 포함 된 문서를 검색하는 데 사용됩니다.
클래스 선언
다음은에 대한 선언입니다. org.apache.lucene.search.PhraseQuery 수업:
public class PhraseQuery
extends Query
클래스 생성자
다음 표는 클래스 생성자를 보여줍니다-
S. 아니. |
생성자 및 설명 |
1 |
PhraseQuery() 빈 구문 쿼리를 생성합니다. |
수업 방법
다음 표는 다른 클래스 메서드를 보여줍니다-
S. 아니. |
방법 및 설명 |
1 |
void add(Term term) 쿼리 구문 끝에 용어를 추가합니다. |
2 |
void add(Term term, int position) 쿼리 구문 끝에 용어를 추가합니다. |
삼 |
Weight createWeight(Searcher searcher) 전문가 :이 쿼리에 대한 적절한 가중치 구현을 구성합니다. |
4 |
boolean equals(Object o) 객체 o가 이것과 같으면 참을 반환합니다. |
5 |
void extractTerms(Set<Term> queryTerms) 전문가 :이 쿼리에서 발생하는 모든 용어를 용어 집합에 추가합니다. |
6 |
int[] getPositions() 이 구에서 용어의 상대적 위치를 반환합니다. |
7 |
int getSlop() 슬롭을 반환합니다. |
8 |
Term[] getTerms() 이 구의 용어 집합을 반환합니다. |
9 |
int hashCode() 이 개체의 해시 코드 값을 반환합니다. |
10 |
Query rewrite(IndexReader reader) 전문가 : 쿼리를 기본 쿼리로 다시 작성하기 위해 호출됩니다. |
11 |
void setSlop(int s) 쿼리 구문의 단어 사이에 허용되는 다른 단어 수를 설정합니다. |
12 |
String toString(String f) 이 쿼리의 사용자가 읽을 수있는 버전을 인쇄합니다. |
상속 된 메서드
이 클래스는 다음 클래스에서 메서드를 상속합니다-
- org.apache.lucene.search.Query
- java.lang.Object
용법
private void searchUsingPhraseQuery(String[] phrases)
throws IOException, ParseException {
searcher = new Searcher(indexDir);
long startTime = System.currentTimeMillis();
PhraseQuery query = new PhraseQuery();
query.setSlop(0);
for(String word:phrases) {
query.add(new Term(LuceneConstants.FILE_NAME,word));
}
//do the search
TopDocs hits = searcher.search(query);
long endTime = System.currentTimeMillis();
System.out.println(hits.totalHits +
" documents found. Time :" + (endTime - startTime) + "ms");
for(ScoreDoc scoreDoc : hits.scoreDocs) {
Document doc = searcher.getDocument(scoreDoc);
System.out.println("File: "+ doc.get(LuceneConstants.FILE_PATH));
}
searcher.close();
}
예제 애플리케이션
PhraseQuery를 사용하여 검색을 테스트하기 위해 테스트 Lucene 애플리케이션을 작성하겠습니다.
단계 |
기술 |
1 |
Lucene-First Application 장에 설명 된대로 com.tutorialspoint.lucene 패키지 아래에 이름이 LuceneFirstApplication 인 프로젝트를 작성하십시오 . 또한 Lucene-First Application 장 에서 만든 프로젝트 를이 장에서 검색 프로세스를 이해하는 데 사용할 수 있습니다 . |
2 |
Lucene- 첫 번째 애플리케이션 장에 설명 된대로 LuceneConstants.java 및 Searcher.java 를 작성하십시오 . 나머지 파일은 변경하지 마십시오. |
삼 |
아래 언급 된대로 LuceneTester.java 를 작성하십시오 . |
4 |
응용 프로그램을 정리하고 빌드하여 비즈니스 논리가 요구 사항에 따라 작동하는지 확인합니다. |
LuceneConstants.java
이 클래스는 샘플 애플리케이션에서 사용할 다양한 상수를 제공하는 데 사용됩니다.
package com.tutorialspoint.lucene;
public class LuceneConstants {
public static final String CONTENTS = "contents";
public static final String FILE_NAME = "filename";
public static final String FILE_PATH = "filepath";
public static final int MAX_SEARCH = 10;
}
Searcher.java
이 클래스는 원시 데이터에 작성된 색인을 읽고 Lucene 라이브러리를 사용하여 데이터를 검색하는 데 사용됩니다.
package com.tutorialspoint.lucene;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.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.store.FSDirectory;
import org.apache.lucene.util.Version;
public class Searcher {
IndexSearcher indexSearcher;
QueryParser queryParser;
Query query;
public Searcher(String indexDirectoryPath) throws IOException {
Directory indexDirectory =
FSDirectory.open(new File(indexDirectoryPath));
indexSearcher = new IndexSearcher(indexDirectory);
queryParser = new QueryParser(Version.LUCENE_36,
LuceneConstants.CONTENTS,
new StandardAnalyzer(Version.LUCENE_36));
}
public TopDocs search( String searchQuery)
throws IOException, ParseException {
query = queryParser.parse(searchQuery);
return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);
}
public TopDocs search(Query query) throws IOException, ParseException {
return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);
}
public Document getDocument(ScoreDoc scoreDoc)
throws CorruptIndexException, IOException {
return indexSearcher.doc(scoreDoc.doc);
}
public void close() throws IOException {
indexSearcher.close();
}
}
LuceneTester.java
이 클래스는 Lucene 라이브러리의 검색 기능을 테스트하는 데 사용됩니다.
package com.tutorialspoint.lucene;
import java.io.IOException;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
public class LuceneTester {
String indexDir = "E:\\Lucene\\Index";
String dataDir = "E:\\Lucene\\Data";
Searcher searcher;
public static void main(String[] args) {
LuceneTester tester;
try {
tester = new LuceneTester();
String[] phrases = new String[]{"record1.txt"};
tester.searchUsingPhraseQuery(phrases);
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
private void searchUsingPhraseQuery(String[] phrases)
throws IOException, ParseException {
searcher = new Searcher(indexDir);
long startTime = System.currentTimeMillis();
PhraseQuery query = new PhraseQuery();
query.setSlop(0);
for(String word:phrases) {
query.add(new Term(LuceneConstants.FILE_NAME,word));
}
//do the search
TopDocs hits = searcher.search(query);
long endTime = System.currentTimeMillis();
System.out.println(hits.totalHits +
" documents found. Time :" + (endTime - startTime) + "ms");
for(ScoreDoc scoreDoc : hits.scoreDocs) {
Document doc = searcher.getDocument(scoreDoc);
System.out.println("File: "+ doc.get(LuceneConstants.FILE_PATH));
}
searcher.close();
}
}
데이터 및 인덱스 디렉토리 생성
우리는 record1.txt의 10 개의 텍스트 파일을 사용하여 학생의 이름과 기타 세부 정보를 포함하는 record10.txt를 디렉터리에 넣었습니다. E:\Lucene\Data. 테스트 데이터 . 인덱스 디렉토리 경로는 다음과 같이 생성되어야합니다.E:\Lucene\Index. 챕터 중 인덱싱 프로그램을 실행 한 후Lucene - Indexing Process, 해당 폴더에 생성 된 색인 파일 목록을 볼 수 있습니다.
프로그램 실행
소스, 원시 데이터, 데이터 디렉토리, 색인 디렉토리 및 색인 작성이 완료되면 프로그램을 컴파일하고 실행하여 진행할 수 있습니다. 이렇게하려면LuceneTester.Java 파일 탭이 활성화되어 있고 Run Eclipse IDE에서 사용 가능한 옵션 또는 Ctrl + F11 컴파일하고 실행하려면 LuceneTester신청. 응용 프로그램이 성공적으로 실행되면 Eclipse IDE의 콘솔에 다음 메시지가 인쇄됩니다.
1 documents found. Time :14ms
File: E:\Lucene\Data\record1.txt