public class SolrFacetTest {
@Test
public void jqxxFacet() {
SolrQuery query = new SolrQuery("*:*");
query.setStart(0);
query.setRows(0);
// 会显示全部,不然只会默认的展示10或者100个数据
query.setFacetLimit(-1);
query.setFacet(true);
query.addFacetField("BJLXDM_s", "BJLXDM_FORMAT_s");
// 统计为0的不返回
query.setFacetMinCount(1);
query.setFacetSort(FacetParams.FACET_SORT_COUNT);
QueryResponse response = SolrSample.execute(query, "http://172.30.10.31:10180/solr/XS_JJDXX");
List<FacetField> facets = response.getFacetFields();//返回的facet列表
for (FacetField facet : facets) {
System.out.println("----------------");
List<FacetField.Count> counts = facet.getValues();
for (FacetField.Count count : counts) {
System.out.println(count.getName() + ":" + count.getCount());
}
System.out.println();
}
}
@Test
public void jqxxFacetPivot() {
SolrQuery query = new SolrQuery("*:*");
query.setFacet(true);
// 多个纬度字段需要拼接在一起
// query.add("facet.pivot", "BJLXDM_s,BJLXDM_FORMAT_s");
query.addFacetPivotField("BJLXDM_s,BJLXDM_FORMAT_s");
QueryResponse response = SolrSample.execute(query, "http://172.30.10.31:10180/solr/XS_JJDXX");
NamedList<List<PivotField>> namedList = response.getFacetPivot();//返回的facet列表
System.out.println("----------------");
Map<String, String> map = new HashMap<>();
if (namedList != null) {
for (int i = 0; i < namedList.size(); i++) {
List<PivotField> pivotList = namedList.getVal(i);
if (pivotList != null) {
for (PivotField pivot : pivotList) {
map.put(pivot.getValue().toString(),
pivot.getPivot() != null ? pivot.getPivot().get(0).getValue().toString() : "");
List<PivotField> fieldList = pivot.getPivot();
if (fieldList != null) {
for (PivotField field : fieldList) {
System.out.println("---");
}
}
}
}
}
}
System.out.println(JsonUtil.toJsonStr(map));
System.out.println("----------------");
}
}
public class SolrSample {
public static QueryResponse execute(SolrQuery query, String url) {
assert null != query && null != url && !url.isEmpty();
SolrClient client = new HttpSolrClient.Builder().withBaseSolrUrl(url).build();
try {
return client.query(query);
} catch (SolrServerException | IOException e) {
throw new RuntimeException(e);
} finally {
try {
if (client != null) client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}