我正在尝试对结果进行分组,以便按类别进行分组。
SearchResponse response = client.prepareSearch("search")
.addAggregation(AggregationBuilders.terms("category").field("category").size(0))
.execute()
.actionGet();
上面的代码创建了聚合,但我遇到了一个问题,带有连字符的字符串正在被分离并放入他们自己的'Bucket'。
根据我的阅读,我需要更改映射设置,以便不分析类别,但我不知道如何做到这一点。这是在写入Elasticsearch或阅读时完成的吗?它是如何设置的?
答案 0 :(得分:1)
步骤1)首先在json文件中创建Elasticsearch类型的映射,
例如。 resources/Customer.json
{
"Customer" : {
"settings" : {
},
"properties" : {
"category" : { "type":"String" , "index" : "not_analyzed"}
}
}
}
}
}
步骤2)创建一个java方法,从json文件应用映射,(参见完整示例here)
class EsUtils {
public static Client client
public static void applyMapping(String index, String type, String location) throws Exception {
String source = readJsonDefn(location);
if (source != null) {
PutMappingRequestBuilder pmrb = client.admin().indices()
.preparePutMapping(index)
.setType(type);
pmrb.setSource(source);
MappingListener mappingListener = new MappingListener(pmrb)
// Create type and mapping
Thread thread = new Thread(mappingListener)
thread.start();
while (!mappingListener.processComplete.get()) {
System.out.println("not complete yet. Waiting for 100 ms")
Thread.sleep(100);
}
} else {
System.out.println("mapping error");
}
}
public static String readJsonDefn(String url) throws Exception {
//implement it the way you like
StringBuffer bufferJSON = new StringBuffer();
FileInputStream input = new FileInputStream(new File(url).absolutePath);
DataInputStream inputStream = new DataInputStream(input);
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = br.readLine()) != null) {
bufferJSON.append(line);
}
br.close();
return bufferJSON.toString();
}
}
步骤3)调用applyMapping()方法传递你的es客户端
String index = "search"; //yourIndex
String type = "Customer";
String location = "resources/Customer.json";
EsUtils.client = yourClient; //pass your client
EsUtils.applyMapping(index, type, location);
步骤4)查询,
SearchRequestBuilder builder = client.prepareSearch("search");
builder.addAggregation(AggregationBuilders.terms("categoryterms")
.field("category").size(0))
SearchResponse response = builder.execute().actionGet();