电商项目前台搜索服务es实现

一、服务搭建

1.依赖导入

除了常见的依赖,特别要注意的是es的依赖,mq的依赖。

 <dependencies>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
      </dependency>
      <!--mybatis-->
      <dependency>
          <groupId>org.mybatis.spring.boot</groupId>
          <artifactId>mybatis-spring-boot-starter</artifactId>
      </dependency>
      <!-- nacos客户端依赖包 -->
      <dependency>
          <groupId>com.alibaba.cloud</groupId>
          <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
      </dependency>
      <!--feign客户端依赖-->
      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-openfeign</artifactId>
      </dependency>
      <!--引入HttpClient依赖-->
      <dependency>
          <groupId>io.github.openfeign</groupId>
          <artifactId>feign-httpclient</artifactId>
      </dependency>

      <dependency>
          <groupId>com.baomidou</groupId>
          <artifactId>mybatis-plus-boot-starter</artifactId>
      </dependency>

      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid-spring-boot-starter</artifactId>
      </dependency>

      <!-- 此处是你的store_common_feign模块的gav,如果不一致,需要改进,注意,需要放入maven本地库!-->
      <dependency>
          <artifactId>store-commons</artifactId>
          <groupId>com.atguigu</groupId>
          <version>1.0.0</version>
      </dependency>

      <!--AMQP依赖,包含RabbitMQ-->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-amqp</artifactId>
      </dependency>

      <!-- 导入es依赖 -->
      <dependency>
          <groupId>org.elasticsearch.client</groupId>
          <artifactId>elasticsearch-rest-high-level-client</artifactId>
      </dependency>

</dependencies>

配置类省略,这里无需配置数据库

2.启动类

启动类要排除自动导入数据库配置,否则出现配置连接池异常。

//排除自动导入数据库配置,否者出现为配置连接池信息异常
@SpringBootApplication(exclude = {
        DataSourceAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class,
        DruidDataSourceAutoConfigure.class ,
        HibernateJpaAutoConfiguration.class}).
public class SearchApplication {

    public static void main(String[] args) {
        System.out.println("SearchApplication.main-----");
        SpringApplication.run(SearchApplication.class,args);
        System.out.println("SearchApplication.main+++++");
    }
}

网关省略

3.(1)数据同步时机,在启动就进行商品服务数据查询和同步。(2)商品服务DML动作,都需要通知搜索服务同步。

二、商品展示功能实现

1.商品服务实现商品展示功能

搜索服务展示全部商品需要调用商品服务展示商品接口,通过feign调用。

/product/list

/**
 * 查询全部商品信息
 *
 * @return
 */
@Override
public List<Product> list() {

    List<Product> products = productMapper.selectList(null);

    return products;
}

2.定义商品feignClient

/**
 * projectName: b2c-cloud-store
 *
 * description:商品客户端
 */
@FeignClient(value = "product-service")
public interface ProductClient {

    /**
     * 商品全部数据调用
     * @return
     */
    @GetMapping("/product/list")
    List<Product> list();
}

3.准备商品索引创建DSL语句!

将商品名称,标题以及详细描述添加到all字段,直接使用all字段搜索即可。

# 删除索引结构
DELETE /product


# 创建商品索引!
# 根据多列搜索性能较差,组成成一列搜索提高性能
PUT /product
{
  "mappings": {
    "properties": {
      "productId":{
        "type": "integer"
      },
      "productName":{
        "type": "text",
        "analyzer": "ik_smart",
        "copy_to": "all"
      },
      "categoryId":{
        "type": "integer"
      },
      "productTitle":{
        "type": "text",
        "analyzer": "ik_smart",
        "copy_to": "all"
      },
      "productIntro":{
        "type":"text",
        "analyzer": "ik_smart",
        "copy_to": "all"
      },
      "productPicture":{
        "type": "keyword",
        "index": false
      },
      "productPrice":{
        "type": "double",
        "index": true
      },
      "productSellingPrice":{
        "type": "double"
      },
      "productNum":{
        "type": "integer"
      },
      "productSales":{
        "type": "integer"
      },
      "all":{
        "type": "text",
        "analyzer": "ik_max_word"
      }
    }
  }
}



#查询索引
GET /product/_mapping

#全部查询

GET /product/_search
{
  "query": {
      "match_all": {
        
      }
  }
}

#关键字查询

GET /product/_search
{
  "query": {
     "match": {
       "all": "最好"
     }
  }

}


# 关键字 和 添加分页
GET /product/_search
{
  "query": {
     "match": {
       "all": "最好"
     }
  },
  "from": 0,
  "size": 1

}



# 添加数据
POST /product/_doc/1
{
  "productId":1,
  "productName":"雷碧",
  "productTitle":"最好的碳酸饮料",
  "categoryId":1,
  "productIntro":"硫酸+煤炭制品最好的产品!",
  "productPicture":"http://www.baidu.com",
  "productPrice":10.5,
  "productSellingPrice":6.0,
  "productNum":10,
  "productSales":5
}

# 删除数据
DELETE /product/_doc/1

以上添加到es中,使用kibana添加索引即可。

 3.准备商品doc模型

添加商品Doc实体类,定义all字段,重新构造方法,传入product参数,注意Product类中加@JsonIgnoreProperties(ignoreUnknown = true)。

@Data
@NoArgsConstructor
public class ProductDoc extends Product {

    /**
     * 用于模糊查询字段,由商品名,标题和描述组成
     */
    private String all;

    public ProductDoc(Product product) {
        super(product.getProductId(),product.getProductName(),
                product.getCategoryId(),product.getProductTitle(),
                product.getProductIntro(),product.getProductPicture(),
                product.getProductPrice(),product.getProductSellingPrice(),
                product.getProductNum(),product.getProductSales());
        this.all = product.getProductName()+product.getProductTitle()+product.getProductIntro();
    }
}

4.导入数据,添加配置类

mq序列化方式选择json,构建es客户端对象,并纳入容器管理

/**
 * projectName: b2c-cloud-store
 * description: 消息队列配置
 */
@Configuration
public class SearchConfiguration {

    /**
     * mq序列化方式,选择json!
     * @return
     */
    @Bean
    public MessageConverter messageConverter(){

        return new Jackson2JsonMessageConverter();
    }
    
    /**
     * es客户端添加到ioc容器
     * @return
     */
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client =
                new RestHighLevelClient(
                        RestClient.builder(HttpHost.create("http://自己的es服务地址:9200")));

        return client;
    }
}

5.修改启动类

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@EnableFeignClients(clients = ProductClient.class)
public class SearchApplication {

    public static void main(String[] args) {
        SpringApplication.run(SearchApplication.class,args);
    }
}

6.程序启动监控

监控程序启动,初始化es数据。

初始化逻辑:在启动时就执行商品查询,然后判断是否存在es索引,用getindexrequest获取,对象传入索引名称。如果不存在索引就创建索引,然后删除全部数据,然后重新批量插入数据。

es入门常见的用法可以参照这篇博客:http://t.csdnimg.cn/QsBAm

@Component
@Slf4j
public class SpringBootListener implements ApplicationRunner {

    /**
     * 在此方法完成es数据的同步
     * 1.判断es中的product索引是否存在
     * 2.如果不存在,java代码创建一个
     * 3.如果存在,删除原来的数据
     * 4.查询商品全部数据
     * 5.进行es库的更新工作(插入)
     * @param args
     * @throws Exception
     */
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ProductClient productClient;

    private String indexStr="{\\n\" +\n" +
            "            \"  \\\"mappings\\\": {\\n\" +\n" +
            "            \"    \\\"properties\\\": {\\n\" +\n" +
            "            \"      \\\"productId\\\":{\\n\" +\n" +
            "            \"        \\\"type\\\": \\\"integer\\\"\\n\" +\n" +
            "            \"      },\\n\" +\n" +
            "            \"      \\\"productName\\\":{\\n\" +\n" +
            "            \"        \\\"type\\\": \\\"text\\\",\\n\" +\n" +
            "            \"        \\\"analyzer\\\": \\\"ik_smart\\\",\\n\" +\n" +
            "            \"        \\\"copy_to\\\": \\\"all\\\"\\n\" +\n" +
            "            \"      },\\n\" +\n" +
            "            \"      \\\"categoryId\\\":{\\n\" +\n" +
            "            \"        \\\"type\\\": \\\"integer\\\"\\n\" +\n" +
            "            \"      },\\n\" +\n" +
            "            \"      \\\"productTitle\\\":{\\n\" +\n" +
            "            \"        \\\"type\\\": \\\"text\\\",\\n\" +\n" +
            "            \"        \\\"analyzer\\\": \\\"ik_smart\\\",\\n\" +\n" +
            "            \"        \\\"copy_to\\\": \\\"all\\\"\\n\" +\n" +
            "            \"      },\\n\" +\n" +
            "            \"      \\\"productIntro\\\":{\\n\" +\n" +
            "            \"        \\\"type\\\":\\\"text\\\",\\n\" +\n" +
            "            \"        \\\"analyzer\\\": \\\"ik_smart\\\",\\n\" +\n" +
            "            \"        \\\"copy_to\\\": \\\"all\\\"\\n\" +\n" +
            "            \"      },\\n\" +\n" +
            "            \"      \\\"productPicture\\\":{\\n\" +\n" +
            "            \"        \\\"type\\\": \\\"keyword\\\",\\n\" +\n" +
            "            \"        \\\"index\\\": false\\n\" +\n" +
            "            \"      },\\n\" +\n" +
            "            \"      \\\"productPrice\\\":{\\n\" +\n" +
            "            \"        \\\"type\\\": \\\"double\\\",\\n\" +\n" +
            "            \"        \\\"index\\\": true\\n\" +\n" +
            "            \"      },\\n\" +\n" +
            "            \"      \\\"productSellingPrice\\\":{\\n\" +\n" +
            "            \"        \\\"type\\\": \\\"double\\\"\\n\" +\n" +
            "            \"      },\\n\" +\n" +
            "            \"      \\\"productNum\\\":{\\n\" +\n" +
            "            \"        \\\"type\\\": \\\"integer\\\"\\n\" +\n" +
            "            \"      },\\n\" +\n" +
            "            \"      \\\"productSales\\\":{\\n\" +\n" +
            "            \"        \\\"type\\\": \\\"integer\\\"\\n\" +\n" +
            "            \"      },\\n\" +\n" +
            "            \"      \\\"all\\\":{\\n\" +\n" +
            "            \"        \\\"type\\\": \\\"text\\\",\\n\" +\n" +
            "            \"        \\\"analyzer\\\": \\\"ik_max_word\\\"\\n\" +\n" +
            "            \"      }\\n\" +\n" +
            "            \"    }\\n\" +\n" +
            "            \"  }\\n\" +\n" +
            "            \"}";
    @Override
    public void run(ApplicationArguments args) throws Exception {
        GetIndexRequest getIndexRequest=new GetIndexRequest("product");
        //判断是否存在
        boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        //存在查询删除
        if(exists){
            DeleteByQueryRequest deleteByQueryRequest=new DeleteByQueryRequest("product");
            deleteByQueryRequest.setQuery(QueryBuilders.matchAllQuery());
            restHighLevelClient.deleteByQuery(deleteByQueryRequest,RequestOptions.DEFAULT);
        }else{
            //不存在创建索引
            CreateIndexRequest createIndexRequest=new CreateIndexRequest("product");
            createIndexRequest.source(indexStr, XContentType.JSON);
            restHighLevelClient.indices().create(createIndexRequest,RequestOptions.DEFAULT);
        }
        //查询全部数据
        List<Product> productList=productClient.allList();

        //遍历批量数据插入
        BulkRequest bulkRequest=new BulkRequest();
        ObjectMapper objectMapper=new ObjectMapper();
        for (Product product : productList) {
            ProductDoc productDoc=new ProductDoc(product);
        //插入数据的作用
            IndexRequest indexRequest=new IndexRequest("product").id(product.getProductId().toString());
	//productDoc转成JSON放入
            String json = objectMapper.writeValueAsString(productDoc);
            indexRequest.source(json,XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);
    }
}

以上完成es的数据同步操作。

三、商品搜索服务

1.准备实体类

定义ProductParamSearch参数实体类,包含字段有search 查询关键字,以及分页字段:currentPage和pageSize。

2.定义接口

定义接口/search/product根据关键字和分页参数,进行es索引查询,并将结果封装到R中,返回商品服务即可。

@RestController
@RequestMapping("search")
public class SearchController {

    @Autowired
    private SearchService searchService;

    @PostMapping("product")
    public R productList(@RequestBody ProductParamsSearch productParamsSearch) throws JsonProcessingException {


        return searchService.search(productParamsSearch);
    }

}

3.实现类

实现逻辑

首先判断关键字是否为空,为空就查询全部,调用searchRequest.source().query(QueryBuilders.matchAllQuery)进行查询

否则就根据关键字对all进行查询,之后设置分页参数,设置返回结果response,调用es客户端的search方法获取结果,然后解析结果,解析es查询结果汇总的hits数目用于统计关键字查询商品数量,对获取到的结果进行遍历,获取单独的JSON数据,把其加add到结果集合中。

@Autowired
private RestHighLevelClient client;

/**
 * 商品搜索
 * @param productParamsSearch
 * @return
 */
@Override
public R search(ProductParamsSearch productParamsSearch) throws JsonProcessingException {

    SearchRequest searchRequest = new SearchRequest("product");

    if (StringUtils.isEmpty(productParamsSearch.getSearch())){
        //如果为null,查询全部
        searchRequest.source().query(QueryBuilders.matchAllQuery());
    }else{
        //不为空 all字段进行搜索
        searchRequest.source().query(QueryBuilders.matchQuery("all",productParamsSearch.getSearch()));
    }

    //设置分页参数
    searchRequest.source().from(productParamsSearch.getFrom());
    searchRequest.source().size(productParamsSearch.getSize());

    SearchResponse response = null;
    try {
        response = client.search(searchRequest, RequestOptions.DEFAULT);
    } catch (IOException e) {
        throw  new RuntimeException(e);
    }

    //结果集解析
    //获取集中的结果
    SearchHits hits = response.getHits();
    //获取符合的数量
    long total = hits.getTotalHits().value;

    SearchHit[] items = hits.getHits();

    List<Product> productList = new ArrayList<>();
    ObjectMapper objectMapper = new ObjectMapper();

    for (SearchHit item : items) {
        //获取单挑json数据
        String json = item.getSourceAsString();
        Product product = objectMapper.readValue(json, Product.class);
        productList.add(product);
    }

    return R.ok(null,productList,total);
}

4.定义Client接口,方便商品服务调用完成搜索功能。

  • 16
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值