我是elasticsearch的新手,并试图通过遵循文章https://www.elastic.co/blog/you-complete- me来集成应用程序的自动完成功能。
我遵循以下方法进行相同操作。
活动班
public class Event { private Long eventId; private Long catalogId; private Long orgId; private String orgName; private String catalogName; private String name; private String eventStatus; ..... }
objectmapper用于将事件对象转换为json字符串。这是插入文档的代码
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(); }
转换代码
private Map<String, Object> convertEventDocumentToMap(Event evt) { return objectMapper.convertValue(evt, Map.class); }
我想创建一个索引,并为name_suggest字段设置完成建议器。我怎样才能达到同样的目的?
任何帮助表示赞赏
这是执行相同操作的解决方案。首先使用映射器创建索引并插入数据
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(); }