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

Shy*_*hil 2 java elasticsearch elastic-stack

我是弹性搜索的新手,并尝试按照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;
.....
    }
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

转换代码

private Map<String, Object> convertEventDocumentToMap(Event evt) {
    return objectMapper.convertValue(evt, Map.class);
}
Run Code Online (Sandbox Code Playgroud)

我想创建一个索引,并为 name_suggest 字段设置完成建议。我怎样才能达到同样的目标?

任何帮助表示赞赏

Shy*_*hil 5

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

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

}
Run Code Online (Sandbox Code Playgroud)