ElasticSearch 使用java代码 查询

准备

(一)加maven依赖

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-elasticsearch</artifactId>
            <version>3.2.9.RELEASE</version>
        </dependency>

(二) 配置application.properties文件

spring.data.elasticsearch.cluster-name=my-es
spring.data.elasticsearch.cluster-nodes=ip:9300

(三) 部分使用到的vo类

插入es中的vo类

@Document(indexName = "es_index_prefix_20201003", type = "es_type", shards = 1, replicas = 0)
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ItemEsSearch {
    @Id
    private String id;

    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String describe;


    @Field(type = FieldType.Keyword)
    private String name;

    @Field(type = FieldType.Keyword)
    private String item;

    @Field(type = FieldType.Date)
    private Date serverTime;
}

es中列名类

public class ItemEsQueryCommon {
    public final static String ITEM = "item";

    public final static String NAME = "name";

    public final static String DESCRIBE = "describe";

    public final static String SERVER_TIME = "serverTime";

    public final static String ID = "_id";
}

(四) 普通分页查询

查询每页数据


   /**
     * es 索引前缀
     */
    public final static String INDEX_PREFIX = "es_index_prefix_";


    /**
     * type
     */
    private final static String INDEX_TYPE = "es_type";


    /**
     * 格式化的时间
     */
    private final static String DATE_FORMATTER = "yyyyMMdd";
    
 @Override
    public List<ItemEsSearch> findInstance(ItemEsQueryVO esQuery, PagerPlugin pagerPlugin) {
        NativeSearchQuery nativeSearchQuery = buildNativeSearchQueryWithPage(esQuery)
                .withPageable(PageRequest.of(pagerPlugin.getCurrPage() - 1, pagerPlugin.getPageSize()))
                       .build();
        Gson gson = new GsonBuilder().setDateFormat("YYYY-MM-dd'T'HH:mm:ss").create();
        return elasticsearchTemplate.query(nativeSearchQuery, response -> {
            List<ItemEsSearch> itemEsSearches = new ArrayList<>();
            SearchHits hits = response.getHits();
            Arrays.stream(hits.getHits()).forEach(h -> {
                String source = h.getSourceAsString();
                ItemEsSearch itemEsSearch = gson.fromJson(source, ItemEsSearch.class);
                itemEsSearch.setId(h.getId());
            
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值