首页 > 解决方案 > 在我的项目中使用 JAVA 实施 Elasticsearch 的最佳方法是什么?

问题描述

我对 elasticseach 完全陌生,我也通过以下两个程序做了一些虚拟应用程序->

1>使用Spring数据elasticsearch(其中我不需要后台运行elasticsearch),只需导入ElasticsearchRepository就可以进行crud操作。

但是在这里我面临一个问题 - 我需要为每种类型的数据(比如说 UserModel 和 UserAddressModel)创建不同的模型类,其中包含一些字段(这将是静态的)。因此,如果稍后我需要在该类型中添加新数据,我还需要在模型类中添加该字段。

那么,我们可以让那个动态吗???

2>在另一个应用程序中,我使用了JAVA TransportClient,通过它我可以进行 crud 操作并可以保存任何数据(这里不使用模型),我也可以动态添加新字段。

所以,我很困惑,根据生产水平的性能,哪一种是进一步推进的最佳方式?还是两者都一样?

使用TransportClient

public class UserResource {

TransportClient client;

public UserResource() throws UnknownHostException {
    client = new PreBuiltTransportClient(Settings.EMPTY)
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

}

@GetMapping("/insert/{id}")
public String insert(@PathVariable final String id) throws IOException {

    IndexResponse response = client.prepareIndex("employee", "id", id)
            .setSource(jsonBuilder()
                    .startObject()
                    .field("fname", "peter")
                    .field("lname", "parker")
                    .field("salary", 1200)
                    .field("teamName", "Development")
                    .endObject()
            )
            .get();
    return response.getResult().toString();
}


@GetMapping("/view/{id}")
public Map<String, Object> view(@PathVariable final String id) {
    GetResponse getResponse = client.prepareGet("employee", "id", id).get();
    System.out.println(getResponse.getSource());


    return getResponse.getSource();
}

@GetMapping("/update/{id}")
public String update(@PathVariable final String id) throws IOException {

    UpdateRequest updateRequest = new UpdateRequest();
    updateRequest.index("employee")
            .type("id")
            .id(id)
            .doc(jsonBuilder()
                    .startObject()
                    .field("gender", "male")
                    .endObject());
    try {
        UpdateResponse updateResponse = client.update(updateRequest).get();
        System.out.println(updateResponse.status());
        return updateResponse.status().toString();
    } catch (InterruptedException | ExecutionException e) {
        System.out.println(e);
    }
    return "Exception";
}

@GetMapping("/delete/{id}")
public String delete(@PathVariable final String id) {

    DeleteResponse deleteResponse = client.prepareDelete("employee", "id", id).get();

    System.out.println(deleteResponse.getResult().toString());
    return deleteResponse.getResult().toString();
}
}

使用Springdata 弹性搜索

public class SearchQueryBuilder {

@Autowired
private ElasticsearchTemplate elasticsearchTemplate;


public List<Users> getAll(String text) {

    QueryBuilder query = QueryBuilders.boolQuery()
            .should(
                    QueryBuilders.queryStringQuery(text)
                            .lenient(true)
                            .field("name")
                            .field("teamName")
            ).should(QueryBuilders.queryStringQuery("*" + text + "*")
                    .lenient(true)
                    .field("name")
                    .field("teamName"));

    NativeSearchQuery build = new NativeSearchQueryBuilder()
            .withQuery(query)
            .build();

    List<Users> userses = elasticsearchTemplate.queryForList(build, Users.class);

    return userses;
}

数据加载器:

public class Loaders {

@Autowired
ElasticsearchOperations operations;

@Autowired
UsersRepository usersRepository;

@Autowired
VideoRepository videoRepository;

@PostConstruct
@Transactional
public void loadAll(){


    operations.putMapping(Users.class);
    operations.putMapping(Videos.class);
    usersRepository.save(getData());
    videoRepository.save(getVideoData());

}

private List<Users> getData() {
    List<Users> userses = new ArrayList<>();
    userses.add(new Users("peter",123L, "Accounting", 12000L));

    return userses;
}

用户模型

@Document(indexName = "new", type = "users", shards = 1)
public class Users {

private String name;
private Long id;
private String teamName;
private Long salary;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getTeamName() {
    return teamName;
}

public void setTeamName(String teamName) {
    this.teamName = teamName;
}

public Long getSalary() {
    return salary;
}

public void setSalary(Long salary) {
    this.salary = salary;
}

用户存储库

public interface UsersRepository extends ElasticsearchRepository<Users, Long> {
}

标签: javaspringelasticsearchspring-data-elasticsearch

解决方案


如果您有一个 Java 应用程序,那么高级 Java REST 客户端是您的最佳选择 ( https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.5/index.html )。

请注意,TransportClient 已被弃用,并且支持将在第 8 版中删除(请参阅https://www.elastic.co/guide/en/elasticsearch/client/java-api/master/transport-client.html)。因此,仅考虑这一点就比任何性能考虑更重要。

静态和动态映射之间的选择是一个基本的选择——本质上与 Spring elasticsearch 无关。如果您有动态映射,则可以考虑使用动态模板并取消提供字段映射。

过去,Spring ES 项目赶上 ES 版本有点慢,所以请注意,如果您使用 Spring data ES,您升级 ES 版本的能力可能会受到影响。


推荐阅读