@Configuration
@Component
@Log4j2
public class LuceneSearch {
/**
* 创建搜索
* @throws Exception
*/
public void search() throws Exception{
// 1. Create a Directory to tell where to search
Directory directory = FSDirectory. open ( new File( "E:/lucene/index01" )); // Create in the hard disk
// 2. Create an IndexReader
try {
IndexReader indexReader = IndexReader. open (directory);
//3. Create IndexSearch
IndexSearcher based on IndexReader indexSearcher = new IndexSearcher(indexReader);
// 4. Create search
// Create queryParser
Analyzer analyzer = new StandardAnalyzer(Version. LUCENE_35 ); / / Tokenizer
String f = "content" ; // Declare a f to indicate that the search domain to be searched is content
QueryParser queryParser = new QueryParser(Version. LUCENE_35 ,f,analyzer);
String Strquery = "java" ;
// Create a
Query of what the content of the search contains query =queryParser.parse(Strquery); // Indicates that the search domain of the search is the document containing the kite error in the
content // 5. Search and return according to indexSearcher TopDocs 10 : Indicates that 10 TopDocs are
displayed topDocs=indexSearcher.search(query, 10 );
// 6. Get the scoreDocs object
according to topDocs ScoreDoc[] scoreDocs=topDocs. scoreDocs ;
// Traverse
for (ScoreDoc scoreDoc :scoreDocs){
// 7. According to indexSearcher and scoreDocs get Document
Document document= indexSearcher.doc(scoreDoc.doc ) ;
// 8. Get the required value
according to Document String content= document.get( "content" );
String path = document.get("path");
String filename=document.get( "filename" );
log .info( " document id------>" +scoreDoc.doc );
log .info ( " The file name obtained is :" +filename+ "- -------> [its location is : +" +path+ "+ ] " + "+ its content is :-------------------- ------->" +content);
log .info( "<------------------------------- --The name of the obtained file is : " +filename+ "-------> [its location is : +"+path+"+] " + "+ its content is " );
}
// 9. Close
indexReader.close();
}catch (Exception e){
e.printStackTrace ();
}finally {
try {
}catch (Exception e){
e.printStackTrace ();
}
}
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class LuceneSearchTests {
@Autowired
private LuceneIndex luceneIndex;
@Autowired
private LuceneSearch luceneSearch;
/**
* 测试创建索引
*/
@Test
public void CreateSearchTest() throws Exception{
luceneSearch.search();
}
}