基于client 6.7 版本,新版本有些许不同,注意替换
private static void mappingByBuilder(RestHighLevelClient highLevelClient, String index,String type){
try {
// 删除索引
try {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
AcknowledgedResponse deleteIndexResponse = highLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
// 指示是否所有节点都已确认请求
LOG.info("deleteIndexResponse :{}",deleteIndexResponse.toString());
} catch (ElasticsearchException exception) {
if (exception.status() == RestStatus.NOT_FOUND) {
LOG.info("deleteIndexResponse not such index");
}
}
CreateIndexRequest request = new CreateIndexRequest(index);
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.startObject("properties");
{
builder.startObject("title");
{
builder.field("type", "text").field("analyzer", "ik_max_word");
builder.startObject("fields");
{
builder.startObject("suggest");
{
builder.field("type", "completion").field("analyzer", "ik_max_word");
builder.field("search_analyzer","ik_smart");
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
builder.startObject("content");
{
builder.field("type", "text").field("analyzer", "ik_max_word");
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
request.mapping(builder);
CreateIndexResponse createIndexResponse = highLevelClient.indices().create(request, RequestOptions.DEFAULT);
LOG.info("mappingByBuilder response is :{},acknowledged:{}" ,createIndexResponse.toString(), createIndexResponse.index());
} catch (Exception e) {
LOG.error("mappingByBuilder error" ,e);
}
}
/**
* Create a index by XContentBuilder
*/
private static void indexByXContentBuilder(RestHighLevelClient highLevelClient, String index, String type,String id) {
try {
// 删除索引
try {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
AcknowledgedResponse deleteIndexResponse = highLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
// 指示是否所有节点都已确认请求
LOG.info("deleteIndexResponse :{}",deleteIndexResponse.toString());
} catch (ElasticsearchException exception) {
if (exception.status() == RestStatus.NOT_FOUND) {
LOG.info("deleteIndexResponse not such index");
}
}
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
builder.endObject();
IndexRequest indexRequest = new IndexRequest(index, type,id).source(builder);
IndexResponse indexResponse = highLevelClient.index(indexRequest, RequestOptions.DEFAULT);
LOG.info("IndexByXContentBuilder response is {}", indexResponse.toString());
// 删除默认生成的一条记录
DeleteRequest request = new DeleteRequest(index, type,id);
DeleteResponse deleteResponse = highLevelClient.delete( request, RequestOptions.DEFAULT);
LOG.info("deleResponse index {},id{}",deleteResponse.getIndex(),deleteResponse.getId());
} catch (Exception e) {
LOG.error("IndexByXContentBuilder is failed,exception occurred.", e);
}
}
private static void mappingPutByBuilder(RestHighLevelClient highLevelClient, String index){
try {
PutMappingRequest putMappingRequest = new PutMappingRequest(index);
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.startObject("properties");
{
builder.startObject("title");
{
builder.field("type", "text").field("analyzer", "ik_max_word");
builder.startObject("fields");
{
builder.startObject("suggest");
{
builder.field("type", "completion").field("analyzer", "ik_max_word");
builder.field("search_analyzer","ik_smart");
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
builder.startObject("content");
{
builder.field("type", "text").field("analyzer", "ik_max_word");
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
putMappingRequest.source(builder);
AcknowledgedResponse putMappingResponse = highLevelClient.indices().putMapping(putMappingRequest, RequestOptions.DEFAULT);
LOG.info("mappingByBuilder response is :{},acknowledged:{}" ,putMappingResponse.toString(), putMappingResponse.isAcknowledged());
} catch (Exception e) {
LOG.error("mappingByBuilder error" ,e);
}
}
private static void bulk(RestHighLevelClient highLevelClient, String index, String type) {
try {
BulkRequest request = new BulkRequest();
//插入
request.add(new IndexRequest(index, type, "1").source(
XContentFactory.jsonBuilder().startObject().field("title", "大话西游电影")
.field("content", "大话西游的电影时隔20年即将在2017年4月重映").endObject()));
//插入
request.add(new IndexRequest(index, type, "2").source(
XContentFactory.jsonBuilder().startObject().field("title","大话西游小说")
.field("content","某知名网络小说作家已经完成了大话西游同名小说的出版").endObject()));
request.add(new IndexRequest(index, type, "3").source(
XContentFactory.jsonBuilder().startObject().field("title","大话西游手游")
.field("content","网易游戏近日出品了大话西游经典IP的手游,正在火爆内测中").endObject()));
request.add(new IndexRequest(index, type, "4").source(
XContentFactory.jsonBuilder().startObject().field("title","tring out Elasticsearch")
.field("content","tring out Elasticsearch ,tring out Elasticsearch").endObject()));
BulkResponse bulkResponse = highLevelClient.bulk(request, RequestOptions.DEFAULT);
if (RestStatus.OK.equals((bulkResponse.status()))) {
LOG.info("Bulk is successful");
} else {
LOG.info("Bulk is failed");
}
} catch (Exception e) {
LOG.error("Bulk is failed,exception occurred.", e);
}
}
private static void searchSuggest(RestHighLevelClient highLevelClient,String index,String type,String tmptitle){
try {
SearchRequest searchRequest = new SearchRequest(index);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
CompletionSuggestionBuilder completionSuggestionBuilder = SuggestBuilders.completionSuggestion("title.suggest");
completionSuggestionBuilder.prefix(tmptitle).size(10);
SuggestBuilder suggestBuilder = new SuggestBuilder();
suggestBuilder.addSuggestion("title_suggest", completionSuggestionBuilder);
searchSourceBuilder.suggest(suggestBuilder);
searchSourceBuilder.query(QueryBuilders.matchQuery("content","2017"));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
LOG.info("response---:{}",searchResponse.toString());
SearchHits hits = searchResponse.getHits();
Suggest suggest = searchResponse.getSuggest();
CompletionSuggestion completionSuggestion = suggest.getSuggestion("title_suggest");
//处理结果
//用来处理的接受结果
List result = new ArrayList<>();
for(CompletionSuggestion.Entry op: completionSuggestion.getEntries()){
for(CompletionSuggestion.Entry.Option pp : op){
result.add(pp.getText().toString());
}
}
System.out.println(result.toString());
// SearchHits提供有关所有命中的全局信息,例如命中总数或最高得分:
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
String sourceAsString = hit.getSourceAsString();
LOG.info("sourceAsString --{}",sourceAsString);
}
} catch (Exception e) {
e.printStackTrace();
}
}
List list =
Arrays.asList("本月数", "同期数"
, "同期变动率","同期增减","tiying");
String[] array = list.toArray(new String[0]);
List list1 = ikTokenList(highLevelClient, "index", "news", array);
String maxId = getMaxId(highLevelClient, "index");
bulk(highLevelClient,"index","news",list1,maxId);
-------------------------------------------
// 获取最大id
public static String getMaxId(RestHighLevelClient highLevelClient, String index){
try {
SearchRequest searchRequest = new SearchRequest(index);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery()).sort("_uid", SortOrder.DESC).size(1);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
String id = searchResponse.getHits().getHits()[0].getId();
return id;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
-----------------------------------------
// 获取ik 分词token
private static List ikTokenList(RestHighLevelClient highLevelClient, String index, String type, String[] array){
try {
AnalyzeRequest request = new AnalyzeRequest();
request.analyzer("ik_smart");
request.text(array);
AnalyzeResponse response = highLevelClient.indices().analyze(request, RequestOptions.DEFAULT);
List tokens = response.getTokens();
List collect = tokens.stream().map(AnalyzeResponse.AnalyzeToken::getTerm).distinct().collect(Collectors.toList());
LOG.info(collect.toString());
return collect;
} catch (Exception e) {
LOG.error("ikTokenList is failed,exception occurred.", e);
}
return null;
}
--------------------------------------------
// 批量插入
private static void bulk(RestHighLevelClient highLevelClient, String index, String type, List list,String id) {
try {
BulkRequest request = new BulkRequest();
int i1 = Integer.parseInt(id);
for (int i=0;i