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();
}