Bladeren bron

:low_brightness: 增强搜索功能,用淘宝的搜索辅助api

nnkwrik 6 jaren geleden
bovenliggende
commit
1414805cb7

+ 8 - 2
goods-service/src/main/java/io/github/nnkwrik/goodsservice/controller/SearchController.java

@@ -8,9 +8,11 @@ import io.github.nnkwrik.goodsservice.model.vo.SearchIndexPageVo;
 import io.github.nnkwrik.goodsservice.model.vo.inner.GoodsSimpleVo;
 import io.github.nnkwrik.goodsservice.service.SearchService;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
+import java.util.Arrays;
 import java.util.List;
 
 /**
@@ -62,7 +64,8 @@ public class SearchController {
                                                      @RequestParam(value = "page", defaultValue = "1") int page,
                                                      @RequestParam(value = "limit", defaultValue = "10") int size,
                                                      @JWT JWTUser jwtUser) {
-        List<GoodsSimpleVo> goodsListVo = searchService.searchByKeyword(keyword, page, size);
+        List<String> keywordList = Arrays.asList(StringUtils.split(keyword));
+        List<GoodsSimpleVo> goodsListVo = searchService.searchByKeyword(keywordList, page, size);
 
         //数据库改openid的搜索历史
         String openId = null;
@@ -70,8 +73,11 @@ public class SearchController {
             openId = jwtUser.getOpenId();
             searchService.updateUserHistory(openId, keyword);
         }
+
         //加入热门搜索缓存
-        searchCache.add(keyword.toLowerCase());
+        keywordList.stream()
+                .forEach(word -> searchCache.add(word.toLowerCase()));
+
         log.debug("用户 openid=【{}】,通过关键字【{}】搜索商品,搜索结果:{}", openId, keyword, goodsListVo);
         return Response.ok(goodsListVo);
     }

+ 11 - 4
goods-service/src/main/java/io/github/nnkwrik/goodsservice/dao/SearchMapper.java

@@ -28,11 +28,18 @@ public interface SearchMapper {
     List<SearchHistory> findSearchHistory(@Param("user_id") String userId);
 
 
-    @Select("select id, `name`, primary_pic_url, price\n" +
+    @Select("<script>\n" +
+            "select id, `name`, primary_pic_url, price\n" +
             "from goods\n" +
-            "where name like concat(concat('%',#{keyword}),'%') \n" +
-            "order by " + popular_score + " desc")
-    List<Goods> findGoodsByKeyword(@Param("keyword") String keyword);
+            "where\n" +
+            "    <foreach item='item' collection='keywords' open='(' separator='or' close=')'>\n" +
+            "    name like concat(concat('%', #{item}, '%'))\n" +
+            "    </foreach>\n" +
+            "  and is_selling = 1\n" +
+            "  and is_delete = 0\n" +
+            "order by " + popular_score + " desc\n" +
+            "</script>")
+    List<Goods> findGoodsByKeywords(@Param("keywords") List<String> keywords);
 
 
     @Delete("delete from search_history where user_id = #{user_id}")

+ 1 - 1
goods-service/src/main/java/io/github/nnkwrik/goodsservice/service/SearchService.java

@@ -10,7 +10,7 @@ import java.util.List;
  */
 public interface SearchService {
 
-    List<GoodsSimpleVo> searchByKeyword(String keyword, int page, int size);
+    List<GoodsSimpleVo> searchByKeyword(List<String> keywordList, int page, int size);
 
     List<String> getUserHistory(String openId);
 

+ 4 - 2
goods-service/src/main/java/io/github/nnkwrik/goodsservice/service/impl/SearchServiceImpl.java

@@ -7,10 +7,12 @@ import io.github.nnkwrik.goodsservice.model.po.SearchHistory;
 import io.github.nnkwrik.goodsservice.model.vo.inner.GoodsSimpleVo;
 import io.github.nnkwrik.goodsservice.service.SearchService;
 import io.github.nnkwrik.goodsservice.util.PO2VO;
+import org.apache.commons.lang.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
+import java.util.Arrays;
 import java.util.List;
 import java.util.stream.Collectors;
 
@@ -26,9 +28,9 @@ public class SearchServiceImpl implements SearchService {
 
 
     @Override
-    public List<GoodsSimpleVo> searchByKeyword(String keyword, int page, int size) {
+    public List<GoodsSimpleVo> searchByKeyword(List<String> keywordList, int page, int size) {
         PageHelper.startPage(page, size);
-        List<Goods> goodsList = searchMapper.findGoodsByKeyword(keyword);
+        List<Goods> goodsList = searchMapper.findGoodsByKeywords(keywordList);
         return PO2VO.convertList(goodsList,GoodsSimpleVo.class);
     }
 

+ 8 - 3
goods-service/src/main/java/io/github/nnkwrik/goodsservice/util/PO2VO.java

@@ -12,6 +12,7 @@ import java.util.stream.Collectors;
 
 /**
  * po转vo
+ *
  * @author nnkwrik
  * @date 18/11/15 18:00
  */
@@ -19,6 +20,7 @@ public class PO2VO {
 
     /**
      * po转vo
+     *
      * @param po
      * @param voClass vo的类型
      * @param <T>
@@ -40,6 +42,7 @@ public class PO2VO {
 
     /**
      * poList转voList
+     *
      * @param poList
      * @param voClass vo的类型
      * @param <T>
@@ -54,6 +57,7 @@ public class PO2VO {
 
     /**
      * 把po中的Date对象转换成String,并对vo进行赋值
+     * 不存在Date对象时则什么都不做
      *
      * @param po
      * @param vo
@@ -65,15 +69,16 @@ public class PO2VO {
         BeanWrapper voWrapper = new BeanWrapperImpl(vo);
 
 
-        for (PropertyDescriptor pd : poWrapper.getPropertyDescriptors()) {
+        for (PropertyDescriptor pd : voWrapper.getPropertyDescriptors()) {
             Object date;
+            String fieldName = pd.getDisplayName();
             if (pd.getPropertyType() == Date.class
-                    && (date = poWrapper.getPropertyValue(pd.getDisplayName())) != null) {
+                    && (date = poWrapper.getPropertyValue(fieldName)) != null) {
 
                 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                 String formatted = formatter.format(date);
 
-                voWrapper.setPropertyValue(pd.getDisplayName(), formatted);
+                voWrapper.setPropertyValue(fieldName, formatted);
 
             }
         }

+ 22 - 21
wx-front/pages/search/search.js

@@ -7,7 +7,7 @@ Page({
     keywrod: '',
     searchStatus: false,
     goodsList: [],
-    // helpKeyword: [],
+    helpKeyword: [],
     historyKeyword: [],
     // categoryFilter: false,
     // currentSortType: 'default',
@@ -47,33 +47,34 @@ Page({
     });
   },
 
-  // inputChange: function (e) {
+  inputChange: function (e) {
 
-  //   this.setData({
-  //     keyword: e.detail.value,
-  //     searchStatus: false
-  //   });
-  //   this.getHelpKeyword();
-  // },
-  // getHelpKeyword: function () {
-  //   let that = this;
-  //   util.request(api.SearchHelper, { keyword: that.data.keyword }).then(function (res) {
-  //     if (res.errno === 0) {
-  //       that.setData({
-  //         helpKeyword: res.data
-  //       });
-  //     }
-  //   });
-  // },
+    this.setData({
+      keyword: e.detail.value,
+      searchStatus: false
+    });
+    this.getHelpKeyword();
+  },
+  getHelpKeyword: function () {
+    let that = this;
+    // 'https://suggest.taobao.com/sug?code=utf-8&q=a'
+    util.request('https://suggest.taobao.com/sug', { code: 'utf-8', q: that.data.keyword }).then(function (res) {
+      
+        that.setData({
+          helpKeyword: res.result
+        });
+      
+    });
+  },
   inputFocus: function () {
     this.setData({
       searchStatus: false,
       goodsList: []
     });
 
-    // if (this.data.keyword) {
-    //   this.getHelpKeyword();
-    // }
+    if (this.data.keyword) {
+      this.getHelpKeyword();
+    }
   },
   clearHistory: function () {
     let that = this;

+ 1 - 1
wx-front/pages/search/search.json

@@ -1,3 +1,3 @@
 {
-    
+  "navigationBarTitleText": "商品搜索"
 }

+ 4 - 3
wx-front/pages/search/search.wxml

@@ -4,13 +4,14 @@
       <image class="icon" src="http://nos.netease.com/mailpub/hxm/yanxuan-wap/p/20150730/style/img/icon-normal/search2-2fb94833aa.png"></image>
       <!-- TODO 输入辅助 -->
       <!-- <input name="input" class="keywrod" focus="true" value="{{keyword}}" confirm-type="search" bindinput="inputChange" bindfocus="inputFocus" bindconfirm="onKeywordConfirm" confirm-type="search" placeholder="{{defaultKeyword}}" /> -->
-            <input name="input" class="keywrod" focus="true" value="{{keyword}}"  bindfocus="inputFocus" bindconfirm="onKeywordConfirm" confirm-type="search" placeholder="{{defaultKeyword}}" />
+            <input name="input" class="keywrod" focus="true" value="{{keyword}}" confirm-type="search" bindinput="inputChange" bindfocus="inputFocus" bindconfirm="onKeywordConfirm" confirm-type="search" placeholder="{{defaultKeyword}}" />
+            <!-- <input name="input" class="keywrod" focus="true" value="{{keyword}}"  bindfocus="inputFocus" bindconfirm="onKeywordConfirm" confirm-type="search" placeholder="{{defaultKeyword}}" /> -->
       <image class="del" wx:if="{{keyword}}" bindtap="clearKeyword" src="http://nos.netease.com/mailpub/hxm/yanxuan-wap/p/20150730/style/img/icon-normal/clearIpt-f71b83e3c2.png"></image>
     </view>
     <view class="right" bindtap="closeSearch">取消</view>
   </view>
   <view class="no-search" wx:if="{{ !searchStatus}}">
-    <view class="serach-keywords search-history" wx:if="{{historyKeyword.length}}">
+    <view class="serach-keywords search-history" wx:if="{{!keyword && historyKeyword.length}}">
       <view class="h">
         <text class="title">历史记录</text>
         <image class="icon" bindtap="clearHistory" src="http://nos.netease.com/mailpub/hxm/yanxuan-wap/p/20150730/style/img/icon-normal/del1-93f0a4add4.png"></image>
@@ -28,7 +29,7 @@
       </view>
     </view>
     <view class="shelper-list" wx:if="{{keyword}}">
-      <view class="item" hover-class="navigator-hover" wx:for="{{helpKeyword}}" bindtap="onKeywordTap" data-keyword="{{item}}">{{item}}</view>
+      <view class="item" hover-class="navigator-hover" wx:for="{{helpKeyword}}" bindtap="onKeywordTap" data-keyword="{{item[0]}}">{{item[0]}}</view>
     </view>
   </view>
 

+ 1 - 1
wx-front/pages/ucenter/about/about.wxml

@@ -2,7 +2,7 @@
   <text class='txt'>
 哈喽! 玩得开心吗? 
 
-我是这个开源项目的作者曾生一个在日本的大学生。
+我是这个开源项目的作者曾生一个在日本的大学生。
 
 这是我第一次尝试用SpringCloud搭建的微信小程序。今后会不定期更新,逐步完善功能。
 如果你觉得这个项目有不足的地方或意见,欢迎在issue中给我留言,也可以通过下面的微信二维码找到我。