java执行es的restclient,在Java REST Client [6.5] API上的ES 6.5中通过映射创建索引

I am new to elastic search and trying to integrate an autocomplete feature for an app by following the article https://www.elastic.co/blog/you-complete-me.

I have followed the below approach to do the same.

Event class

public class Event {

private Long eventId;

private Long catalogId;

private Long orgId;

private String orgName;

private String catalogName;

private String name;

private String eventStatus;

.....

}

An objectmapper is used to convert the event object to json string. Here is the code to insert the document

public String createEventDocument(Event document) throws Exception {

IndexRequest indexRequest = new IndexRequest(INDEX, TYPE, document.idAsString())

.source(convertEventDocumentToMap(document));

//create mapping with a complete field

IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);

return indexResponse.getResult().name();

}

Convert code

private Map convertEventDocumentToMap(Event evt) {

return objectMapper.convertValue(evt, Map.class);

}

I would like to create an index, and setup the completion suggester for the name_suggest field. How can I achieve the same ?

Any help is appreciated

解决方案

Here is the solution to do the same. Create index with mappers first and insert the data

public String createEventDocument(Event document) throws Exception {

GetIndexRequest request = new GetIndexRequest();

request.indices(INDEX);

boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);

if(!exists){

createIndexWithMapping();

}

IndexRequest indexRequest = new IndexRequest(INDEX, TYPE, document.idAsString())

.source(convertEventDocumentToMap(document));

//create mapping with a complete field

IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);

return indexResponse.getResult().name();

}

private boolean createIndexWithMapping() throws IOException {

CreateIndexRequest createIndexRequest = new CreateIndexRequest(INDEX);

XContentBuilder builder = XContentFactory.jsonBuilder();

builder.startObject();

{

builder.startObject( "properties" );

{

builder.startObject( "name_suggest" );

{

builder.field( "type", "completion" );

}

builder.endObject();

}

builder.endObject();

}

builder.endObject();

createIndexRequest.mapping(TYPE,builder);

createIndexRequest.timeout(TimeValue.timeValueMinutes(2));

CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);

return createIndexResponse.isAcknowledged();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值