栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

SrpingBoot-data-elasticsearch

SrpingBoot-data-elasticsearch

添加依赖
	
        org.springframework.boot
        spring-boot-starter-parent
        2.2.3.RELEASE
         
    

    springBoot
    springBoot
    org.example
    springBoot
    1.0-SNAPSHOT


    
        UTF-8
        UTF-8
        1.8
        1.18.12
        8.5.21
    

    
        
            org.projectlombok
            lombok
            ${lombok.version}
            provided
        

        
            org.springframework.boot
            spring-boot-starter-web
            
                
                    org.springframework.boot
                    spring-boot-starter-logging
                
            
        

        
            org.springframework.boot
            spring-boot-starter-actuator
            
                
                    org.springframework.boot
                    spring-boot-starter-logging
                
            
        


        
            org.springframework.boot
            spring-boot-starter-mail
            
                
                    org.springframework.boot
                    spring-boot-starter-logging
                
            
        

        
            org.springframework.boot
            spring-boot-starter-quartz
            
                
                    org.springframework.boot
                    spring-boot-starter-logging
                
            
        


        修复log4j<-->
        
            org.apache.logging.log4j
            log4j-api
            2.17.1
        
        
            org.apache.logging.log4j
            log4j-core
            2.17.1
        
        
            org.apache.logging.log4j
            log4j-slf4j-impl
            2.17.1
        

        
            org.apache.logging.log4j
            log4j-web
            2.17.1
        

        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        

        
            org.springframework.boot
            spring-boot-starter-jdbc
            
                
                    org.springframework.boot
                    spring-boot-starter-logging
                
                
                    org.apache.tomcat
                    tomcat-jdbc
                
            
        


        
        
            org.springframework.data
            spring-data-elasticsearch
            3.2.0.RELEASE
        

        
        
            org.apache.tomcat
            tomcat-dbcp
            8.5.43
        

        
            org.apache.tomcat
            tomcat-jdbc
            ${org.apache.tomcat.tomcat-jdbc.version}
        

    


    
        
            
                kr.motd.maven
                os-maven-plugin
                1.6.2
            
        
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.5.1 
                
                    1.8 
                    1.8 
                    
                        
                            org.projectlombok
                            lombok
                            ${lombok.version}
                        
                        
                    
                
            
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
                org.apache.maven.plugins
                maven-jar-plugin
                
                    
                        *.**
                    
                    
                        
                            true
                            lib/
                            false
                            es.com.DmpApplication
                        
                        
                            ./resources/
                        
                    
                    ${project.build.directory}
                
            

            
                org.apache.maven.plugins
                maven-dependency-plugin
                
                    
                        copy-dependencies
                        package
                        
                            copy-dependencies
                        
                        
                            
                                ${project.build.directory}/lib/
                            
                        
                    
                
            

            
                maven-resources-plugin
                
                    
                        copy-resources
                        package
                        
                            copy-resources
                        
                        
                            
                                
                                    src/main/resources
                                    true
                                
                            
                            ${project.build.directory}/resources
                        
                    
                
            

            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            null
                            null
                        
                    
                    ZIP
                    true
                    ${project.build.directory}
                
                
                    
                        
                            repackage
                        
                        
                        
                    
                
            

            
                org.apache.maven.plugins
                maven-checkstyle-plugin
                3.1.2
                
                    
                        com.puppycrawl.tools
                        checkstyle
                        8.41
                    
                
                
                    
                        checkstyle
                        validate
                        
                            check
                        
                        
                            false
                            true
                            true
                            others/tencent_checks.xml
                        
                    
                
            
        
    

    
        
            alimaven-central
            http://maven.aliyun.com/nexus/content/repositories/central/
            
                true
            
        

        
            jboss-public-repository-group
            http://repository.jboss.org/nexus/content/groups/public
            
                true
            
        

        
            mirrorId
            http://mirrors.tencent.com/nexus/repository/maven-public
            
                true
            
        

    
添加application.properties 配置文件
spring.application.name=S
server.port=18001
server.tomcat.uri-encoding=UTF-8
spring.elasticsearch.rest.uris=106.55.58.166:9200
添加es配置文件类
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

@Configuration
public class EsClientConfig {


    @Value("${spring.elasticsearch.rest.uris}")
    private String host;

    @Bean
    RestHighLevelClient restHighLevelClient() {
        ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(host)                    // es的http连接地址
                .withBasicAuth("root", "root")    // 如果开启了用户名密码验证,则需要加上
                .build();
        return RestClients.create(clientConfiguration).rest();
    }

    @Bean
    ElasticsearchRestTemplate elasticsearchRestTemplate(@Autowired RestHighLevelClient restHighLevelClient) {

        return new ElasticsearchRestTemplate(restHighLevelClient);
    }
}
添加bean类
import io.micrometer.core.lang.Nullable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

@Data
@AllArgsConstructor
@NoArgsConstructor
@document(indexName = "person", type = "_doc", shards = 1, replicas = 1)
public class BizAction {
    @Id
    @Nullable
    private String id;

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

    @Field(type = FieldType.Keyword)
    private Integer age;

    @Override
    public String toString() {
        return "bizAction{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", age='" + age + ''' +
                '}';
    }

//    @Id
//    @Nullable
//    private String id;
//
//    @Field(value = "last-name", type = FieldType.Keyword)
//    private String lastName;
//
//    @Field(type = FieldType.Keyword)
//    private String type;
//
//    @Field(type = FieldType.Integer)
//    private Integer age;

//    @Nullable @Field(name = "birth-date", type = FieldType.Date, format = DateFormat.basic_date)
//    private LocalDate birthDate;
//
//    @Field(type = FieldType.Boolean)
//    private Boolean isDeleted;
//    @Field(type = FieldType.Date, format = DateFormat.basic_date)
//    private LocalDate createTime;
//    @Field(type = FieldType.Date, format = DateFormat.basic_date)
//    private LocalDate updateTime;


}
添加controller
package es.com.controller;
import es.com.orm.BizAction;
import es.com.common.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/dmp/api/estest")
public class ESController {
    private static final Logger logger = LoggerFactory.getLogger(ESController.class);

    @Autowired
    es.com.service.ESService ESService;

    @PostMapping("/create")
    public ApiResponse queryPortraitUin(@RequestBody BizAction person) {
        String personById = ESService.createPerson(person);
        System.out.println(personById.toString());

        return ApiResponse.OK(personById);
    }

    @PostMapping("/query")
    public ApiResponse queryPortrait(@RequestBody BizAction person) {
        BizAction personById = ESService.getPersonById("1");
//        System.out.println(personById.toString());

        return ApiResponse.OK(personById);
    }


}
添加service
package es.com.service;
import es.com.orm.BizAction;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.stereotype.Service;
import java.util.Iterator;

@Service
public class ESService {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;


//    @Autowired
//    private BizActionRepository repository;

    // 根据id查询一条文档
    public BizAction getPersonById(String id) {
        System.out.println(id);
        // 查看当前索引是否存在
        boolean b = elasticsearchRestTemplate.indexExists(BizAction.class);
        // 根据document id 查询文档
        BizAction bizAction = elasticsearchRestTemplate.queryForObject(GetQuery.getById(id), BizAction.class);
        // 根据document id 分页查询文档
        MatchQueryBuilder builder = QueryBuilders.matchQuery("id", "1");
        SearchQuery searchQuery = new NativeSearchQuery(builder).setPageable(PageRequest.of(0, 100));
        AggregatedPage page = elasticsearchRestTemplate.queryForPage(searchQuery, BizAction.class);
        long totalElements = page.getTotalElements(); // 总记录数
        int totalPages = page.getTotalPages();  // 总页数
        int pageNumber = page.getPageable().getPageNumber(); // 当前页号
        Iterator iterator = page.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().toString());
        }
        System.out.println(totalElements);


        return bizAction;
    }

    // 新增一条文档
    public String createPerson(BizAction person) {
        IndexQuery indexQuery = new IndexQueryBuilder()
                .withId(person.getId())
                .withObject(person)
                .withType("_doc")
                .build();
        String documentId = elasticsearchRestTemplate.index(indexQuery);
        return documentId;
    }

    // 高级查询
    public String getdocument() {

        

        MatchQueryBuilder lastUpdateUser = QueryBuilders.matchQuery("person", "1");
        MatchQueryBuilder deleteflag = QueryBuilders.matchQuery("name", "lss");
        //创建bool多条件查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        BoolQueryBuilder mustQuery = boolQueryBuilder.must(lastUpdateUser).must(deleteflag);
        //嵌套索引,需要使用nest查询
        mustQuery.must(QueryBuilders.nestedQuery("entityNodes", QueryBuilders.termQuery("entityNodes.node_type", ""), ScoreMode.None));
        //可以使用should查询,不是必需条件
        BoolQueryBuilder nodeQueryBuilder = QueryBuilders.boolQuery();
        nodeQueryBuilder.should(QueryBuilders.nestedQuery("entityNodes", QueryBuilders.wildcardQuery("entityNodes.parent_ids", "*," + "11" + "*"), ScoreMode.None));
        nodeQueryBuilder.should();
        mustQuery.must(nodeQueryBuilder);
        //查询使用排序
        SortBuilder order = new FieldSortBuilder("lastUpdateTime").order(SortOrder.DESC);
        //可以使用高亮显示,就是html标签
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("")
                .postTags("")
                .field("paperbaseName");//哪个字段高亮
        //使用分页查询
        SearchQuery nativeSearchQueryBuilder = new NativeSearchQueryBuilder()
                .withQuery(mustQuery).withSort(order).withHighlightBuilder(highlightBuilder)
                .withPageable(PageRequest.of(0, 100)).build();
        //进行查询,entityMapper使用默认的也可,EsPaperbase.class是需要自己映射的查询类
        elasticsearchRestTemplate.queryForPage(nativeSearchQueryBuilder, BizAction.class);

        return "";
    }
}

资源: https://download.csdn.net/download/weixin_49761581/76848339

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/711399.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号