Elesticsearch使用总结

发布于:2023-10-25 ⋅ 阅读:(140) ⋅ 点赞:(0)

写在前面

ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于[云计算]中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。

可以这样来对比elasticsearch和数据库
索引(indices) ~~~~~~~~ 数据库(databases)
类型(type) ~~~~~~~~ 数据表(table)
文档(Document)~~~~~~~~ 行(row)
字段(Field) ~~~~~~~~ 列(Columns )

shards:分片数量,默认5
replicas:副本数量,默认1

引入库

implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-elasticsearch', version: '2.7.5'
implementation group: 'org.springframework.data', name: 'spring-data-elasticsearch', version: '4.4.13';

版本对应要求见如下表格: 传送门

Spring Data Release Train Spring Data Elasticsearch Elasticsearch Spring Framework Spring Boot
2023.0 (Ullmann) 5.1.x 8.7.1 6.0.x 3.1.x
2022.0 (Turing) 5.0.x 8.5.3 6.0.x 3.0.x
2021.2 (Raj) 4.4.x[1] 7.17.3 5.3.x 2.7.x
2021.1 (Q) 4.3.x[1] 7.15.2 5.3.x 2.6.x
2021.0 (Pascal) 4.2.x[1] 7.12.0 5.3.x 2.5.x
2020.0 (Ockham) 4.1.x[1] 7.9.3 5.3.2 2.4.x
Neumann 4.0.x[1] 7.6.2 5.2.12 2.3.x
Moore 3.2.x[1] 6.8.12 5.2.12 2.2.x
Lovelace 3.1.x[1] 6.2.2 5.1.19 2.1.x
Kay 3.0.x[1] 5.5.0 5.0.13 2.0.x
Ingalls 2.1.x[1] 2.4.0 4.3.25 1.5.x

配置连接

spring:
  elasticsearch:
    rest:
      uris: 10.10.88.163:9200
      username: root
      password: pass123

配置信息读取:

@RefreshScope
@ConfigurationProperties(ESProperties.PREFIX)
public class ESProperties {

    public static final String PREFIX = "spring.elasticsearch.rest";

    private Boolean enable = true;
    private String uris;

    private String userName;

    /**
     * Secret key是你账户的密码
     */
    private String password;

	private String deviceId;
    }

连接初始化:

@AutoConfiguration
@EnableConfigurationProperties(ESProperties.class)
@ConditionalOnProperty(value = ESProperties.PREFIX + ".enabled", havingValue = "true", matchIfMissing = true)
public class ElasticSearchConfig extends AbstractElasticsearchConfiguration {
    private static final Logger logger = LogManager.getLogger(ElasticSearchConfig.class);

    @Resource
    private ESProperties esProperties;

    @Override
    @Bean(destroyMethod = "close")
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(esProperties.getUris())
                .withBasicAuth(esProperties.getUserName(), esProperties.getPassword())
                .withConnectTimeout(RestClientBuilder.DEFAULT_CONNECT_TIMEOUT_MILLIS)
                .withSocketTimeout(RestClientBuilder.DEFAULT_SOCKET_TIMEOUT_MILLIS)
                .build();
        RestHighLevelClient client = RestClients.create(clientConfiguration).rest();
        try {
            logger.info("connect to elasticsearch:{} ", client.getLowLevelClient().getNodes());
            MainResponse response = client.info(RequestOptions.DEFAULT);
            MainResponse.Version version = response.getVersion();
            logger.info("elasticsearch version:{},lucene version:{}", version.getNumber(), version.getLuceneVersion());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return client;
    }
}

文件配置 spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=io.gamioo.core.elasticsearch.config.ElasticSearchConfig

DAO层:

public interface OperationLogRepository extends ElasticsearchRepository<OperationLog, String> {
//时间匹配
Page<OperationLog> findByAddTimeBetween(LocalDateTime startTime, LocalDateTime endTime, Pageable pageable);
//字段后匹配
 Page<OperationLog> findByDeviceIdLike(String deviceId, Pageable pageable);
}
//字段前后匹配
 Page<OperationLog> findByDeviceIdContaining(String deviceId, Pageable pageable);
}

操作对象:

@ApiModel(value = "operation_log", description = "操作日志")
@Document(indexName = "operation_log_*")
public class OperationLog {
    @Id
    private String id;
    @ApiModelProperty("创建时间")
    @Field(name = "addTime", type = FieldType.Date, format = DateFormat.custom, pattern = "yyyy-MM-dd'T'HH:mm:ssz")
    private Date addTime;
    }

逻辑操作:

    @Resource
    private OperationLogRepository repository;
   @Override
    public Page<OperationLog> findAll(Pageable pageable) {
        return repository.findAll(pageable);
    }


    @Override
    public Page<OperationLog> findByAddTimeBetween(LocalDateTime startTime, LocalDateTime endTime, Pageable pageable) {
        return repository.findByAddTimeBetween(startTime, endTime, pageable);
    }
    

Q&A

1.实际使用中一直报错: missing authentication credentials for REST request
经过多方查证,最后发现报错原因是:配置ES时没添加用户名密码验证

2.org.apache.http.ContentTooLongException: entity content is too long [450975428] for the configured buffer limit [104857600]

总结

以上就是springboot集成es后的一个简单使用,spring封装过后的spring-boot-starter-data-elasticsearch使用起来还是非常方便简单的。


网站公告

今日签到

点亮在社区的每一天
去签到