一尘不染

在Java REST Client [6.5] API上的ES 6.5中通过映射创建索引

elasticsearch

我是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字段设置完成建议器。我怎样才能达到同样的目的?

任何帮助表示赞赏


阅读 956

收藏
2020-06-22

共1个答案

一尘不染

这是执行相同操作的解决方案。首先使用映射器创建索引并插入数据

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

}
2020-06-22