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

2024-03-22

我是弹性搜索新手,并尝试按照这篇文章为应用程序集成自动完成功能https://www.elastic.co/blog/you-complete-me 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();

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Java REST 客户端 [6.5] API 上使用 ES 6.5 中的映射创建索引 的相关文章

随机推荐