@RunWith(SpringRunner.class)
@SpringBootTest(classes = {com.pap.lucene.LuceneAutoConfiguration.class})
@TestPropertySource("classpath:application.properties")
@FixMethodOrder(MethodSorters.JVM)
public class LuceneAutoConfigurationTest {
@Autowired
private SearcherManager searcherManager;
@Autowired
private IndexWriter indexWriter;
@Autowired
private DirectoryTaxonomyWriter taxoWriter;
@Test
public void init() throws Exception {
FacetsConfig facetsConfigInit = new FacetsConfig();
facetsConfigInit.setMultiValued("MCategory", true);
indexDocument(indexWriter, taxoWriter, facetsConfigInit, "pap.net.cn 1", "pap.net.cn of content 1", "alex,gao", "Tag A");
indexDocument(indexWriter, taxoWriter, facetsConfigInit, "pap.net.cn 2", "pap.net.cn of content 2", "alex,pap", "Tag B");
indexDocument(indexWriter, taxoWriter, facetsConfigInit, "pap.net.cn 3", "pap.net.cn of content 3", "gao", "Tag A");
indexDocument(indexWriter, taxoWriter, facetsConfigInit, "pap.net.cn 4", "pap.net.cn of content 4", "gao", "Tag B");
indexWriter.commit();
taxoWriter.commit();
}
@Test
public void search() throws Exception {
Query query = new TermQuery(new Term("content", "content"));
searcherManager.maybeRefresh();
IndexSearcher indexSearcher = searcherManager.acquire();
FacetsCollector facetsCollector = new FacetsCollector();
FacetsCollector.search(indexSearcher, query, 10, facetsCollector);
FacetsConfig facetsConfigSearch = new FacetsConfig();
Facets facets = new FastTaxonomyFacetCounts(new DirectoryTaxonomyReader(taxoWriter), facetsConfigSearch, facetsCollector);
FacetResult category = facets.getTopChildren(10, "Category");
if(category != null) {
for(LabelAndValue labelValues : category.labelValues) {
System.out.println(labelValues.label + " : " + labelValues.value);
}
}
System.out.println("------");
FacetResult MCategory = facets.getTopChildren(10, "MCategory");
if(MCategory != null) {
for(LabelAndValue labelValues : MCategory.labelValues) {
System.out.println(labelValues.label + " : " + labelValues.value);
}
}
}
private static void indexDocument(IndexWriter indexWriter, DirectoryTaxonomyWriter taxoWriter, FacetsConfig facetsConfig, String title, String content, String category, String tag) throws IOException {
Document doc = new Document();
doc.add(new StringField("title", title, Field.Store.YES));
doc.add(new TextField("content", content, Field.Store.YES));
doc.add(new FacetField("Category", category));
for(String tmp :category.split(",")) {
doc.add(new FacetField("MCategory", tmp));
}
doc.add(new FacetField("Tag", tag));
indexWriter.addDocument(facetsConfig.build(taxoWriter, doc));
}
}
评论