国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

這篇具有很好參考價值的文章主要介紹了【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

此筆記內(nèi)容為狂神說SpringBoot整合ElasticSearch部分

目錄

一、SpringBoot整合

1、創(chuàng)建工程

2、導(dǎo)入依賴

導(dǎo)入elasticsearch依賴

提前導(dǎo)入fastjson、lombok

3、創(chuàng)建并編寫配置類

4、創(chuàng)建并編寫實體類

5、測試

索引的操作

文檔的操作

二、ElasticSearch實戰(zhàn)

防京東商城搜索(高亮)

1、工程創(chuàng)建(springboot)

2、基本編碼

①導(dǎo)入依賴

②導(dǎo)入前端素材

③編寫?application.preperties配置文件?

④測試controller和view

⑤編寫Config?

⑥編寫service

⑦編寫controller

⑧測試結(jié)果

3、爬蟲(jsoup)

①搜索京東搜索頁面,并分析頁面

②爬取數(shù)據(jù)(獲取請求返回的頁面信息,篩選出可用的)

4、搜索高亮

①ContentService

②ContentController

③結(jié)果展示

5、前后端分離(簡單使用Vue)

①下載并引入Vue.min.js和axios.js

②修改靜態(tài)頁面

使用term(精確查詢)時遇到的問題


一、SpringBoot整合


1、創(chuàng)建工程

創(chuàng)建一個springboot項目

目錄結(jié)構(gòu)

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

2、導(dǎo)入依賴

注意依賴版本和安裝的版本一致

<properties>
    <java.version>1.8</java.version>
    <!-- 統(tǒng)一版本 -->
    <elasticsearch.version>7.6.1</elasticsearch.version>
</properties>

導(dǎo)入elasticsearch依賴

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

提前導(dǎo)入fastjson、lombok

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.70</version>
</dependency>
<!-- lombok需要安裝插件 -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

3、創(chuàng)建并編寫配置類

@Configuration
public class ElasticSearchConfig {
    // 注冊 rest高級客戶端 
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1",9200,"http")
                )
        );
        return client;
    }
}

4、創(chuàng)建并編寫實體類

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
    private static final long serialVersionUID = -3843548915035470817L;
    private String name;
    private Integer age;
}

5、測試

所有測試均在?SpringbootElasticsearchApplicationTests中編寫

注入?RestHighLevelClient

@Autowired
public RestHighLevelClient restHighLevelClient;

索引的操作

1、索引的創(chuàng)建

// 測試索引的創(chuàng)建, Request PUT liuyou_index
@Test
public void testCreateIndex() throws IOException {
    CreateIndexRequest request = new CreateIndexRequest("liuyou_index");
    CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
    System.out.println(response.isAcknowledged());// 查看是否創(chuàng)建成功
    System.out.println(response);// 查看返回對象
    restHighLevelClient.close();
}

2、索引的獲取,并判斷其是否存在

// 測試獲取索引,并判斷其是否存在
@Test
public void testIndexIsExists() throws IOException {
    GetIndexRequest request = new GetIndexRequest("index");
    boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
    System.out.println(exists);// 索引是否存在
    restHighLevelClient.close();
}

3、索引的刪除

// 測試索引刪除
@Test
public void testDeleteIndex() throws IOException {
    DeleteIndexRequest request = new DeleteIndexRequest("liuyou_index");
    AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
    System.out.println(response.isAcknowledged());// 是否刪除成功
    restHighLevelClient.close();
}

文檔的操作

1、文檔的添加

// 測試添加文檔(先創(chuàng)建一個User實體類,添加fastjson依賴)
@Test
public void testAddDocument() throws IOException {
    // 創(chuàng)建一個User對象
    User liuyou = new User("liuyou", 18);
    // 創(chuàng)建請求
    IndexRequest request = new IndexRequest("liuyou_index");
    // 制定規(guī)則 PUT /liuyou_index/_doc/1
    request.id("1");// 設(shè)置文檔ID
    request.timeout(TimeValue.timeValueMillis(1000));// request.timeout("1s")
    // 將我們的數(shù)據(jù)放入請求中
    request.source(JSON.toJSONString(liuyou), XContentType.JSON);
    // 客戶端發(fā)送請求,獲取響應(yīng)的結(jié)果
    IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
    System.out.println(response.status());// 獲取建立索引的狀態(tài)信息 CREATED
    System.out.println(response);// 查看返回內(nèi)容 IndexResponse[index=liuyou_index,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
}

2、文檔信息的獲取

// 測試獲得文檔信息
@Test
public void testGetDocument() throws IOException {
    GetRequest request = new GetRequest("liuyou_index","1");
    GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
    System.out.println(response.getSourceAsString());// 打印文檔內(nèi)容
    System.out.println(request);// 返回的全部內(nèi)容和命令是一樣的
    restHighLevelClient.close();
}

3、文檔的獲取,并判斷其是否存在

// 獲取文檔,判斷是否存在 get /liuyou_index/_doc/1
@Test
public void testDocumentIsExists() throws IOException {
    GetRequest request = new GetRequest("liuyou_index", "1");
    // 不獲取返回的 _source的上下文了
    request.fetchSourceContext(new FetchSourceContext(false));
    request.storedFields("_none_");
    boolean exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT);
    System.out.println(exists);
}

4、文檔的更新

// 測試更新文檔內(nèi)容
@Test
public void testUpdateDocument() throws IOException {
    UpdateRequest request = new UpdateRequest("liuyou_index", "1");
    User user = new User("lmk",11);
    request.doc(JSON.toJSONString(user),XContentType.JSON);
    UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
    System.out.println(response.status()); // OK
    restHighLevelClient.close();
}

5、文檔的刪除

// 測試刪除文檔
@Test
public void testDeleteDocument() throws IOException {
    DeleteRequest request = new DeleteRequest("liuyou_index", "1");
    request.timeout("1s");
    DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
    System.out.println(response.status());// OK
}

6、文檔的查詢

// 查詢
// SearchRequest 搜索請求
// SearchSourceBuilder 條件構(gòu)造
// HighlightBuilder 高亮
// TermQueryBuilder 精確查詢
// MatchAllQueryBuilder
// xxxQueryBuilder ...
@Test
public void testSearch() throws IOException {
    // 1.創(chuàng)建查詢請求對象
    SearchRequest searchRequest = new SearchRequest();
    // 2.構(gòu)建搜索條件
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    // (1)查詢條件 使用QueryBuilders工具類創(chuàng)建
    // 精確查詢
    TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "liuyou");
    //        // 匹配查詢
    //        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
    // (2)其他<可有可無>:(可以參考 SearchSourceBuilder 的字段部分)
    // 設(shè)置高亮
    searchSourceBuilder.highlighter(new HighlightBuilder());
    //        // 分頁
    //        searchSourceBuilder.from();
    //        searchSourceBuilder.size();
    searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
    // (3)條件投入
    searchSourceBuilder.query(termQueryBuilder);
    // 3.添加條件到請求
    searchRequest.source(searchSourceBuilder);
    // 4.客戶端查詢請求
    SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
    // 5.查看返回結(jié)果
    SearchHits hits = search.getHits();
    System.out.println(JSON.toJSONString(hits));
    System.out.println("=======================");
    for (SearchHit documentFields : hits.getHits()) {
        System.out.println(documentFields.getSourceAsMap());
    }
}

前面的操作都無法批量添加數(shù)據(jù)

// 上面的這些api無法批量增加數(shù)據(jù)(只會保留最后一個source)
@Test
public void test() throws IOException {
    IndexRequest request = new IndexRequest("bulk");// 沒有id會自動生成一個隨機ID
    request.source(JSON.toJSONString(new User("liu",1)),XContentType.JSON);
    request.source(JSON.toJSONString(new User("min",2)),XContentType.JSON);
    request.source(JSON.toJSONString(new User("kai",3)),XContentType.JSON);
    IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
    System.out.println(index.status());// created
}

7、批量添加數(shù)據(jù)

// 特殊的,真的項目一般會 批量插入數(shù)據(jù)
@Test
public void testBulk() throws IOException {
    BulkRequest bulkRequest = new BulkRequest();
    bulkRequest.timeout("10s");
    ArrayList<User> users = new ArrayList<>();
    users.add(new User("liuyou-1",1));
    users.add(new User("liuyou-2",2));
    users.add(new User("liuyou-3",3));
    users.add(new User("liuyou-4",4));
    users.add(new User("liuyou-5",5));
    users.add(new User("liuyou-6",6));
    // 批量請求處理
    for (int i = 0; i < users.size(); i++) {
        bulkRequest.add(
                // 這里是數(shù)據(jù)信息
                new IndexRequest("bulk")
                        .id(""+(i + 1)) // 沒有設(shè)置id 會自定生成一個隨機id
                        .source(JSON.toJSONString(users.get(i)),XContentType.JSON)
        );
    }
    BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
    System.out.println(bulk.status());// ok
}

二、ElasticSearch實戰(zhàn)


防京東商城搜索(高亮)

1、工程創(chuàng)建(springboot)

創(chuàng)建一個springboot工程

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

2、基本編碼

①導(dǎo)入依賴

<properties>
    <java.version>1.8</java.version>
    <elasticsearch.version>7.6.1</elasticsearch.version>
</properties>
<dependencies>
    <!-- jsoup解析頁面 -->
    <!-- 解析網(wǎng)頁 爬視頻可 研究tiko -->
    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.10.2</version>
    </dependency>
    <!-- fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.70</version>
    </dependency>
    <!-- ElasticSearch -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>
    <!-- thymeleaf -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <!-- web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- devtools熱部署 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <!--  -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <!-- lombok 需要安裝插件 -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <!-- test -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

②導(dǎo)入前端素材

導(dǎo)入statis和templates里的文件

鏈接:百度網(wǎng)盤 請輸入提取碼
提取碼:qk8p

③編寫?application.preperties配置文件?

# 更改端口,防止沖突
server.port=9999
# 關(guān)閉thymeleaf緩存
spring.thymeleaf.cache=false

④測試controller和view

@Controller
public class IndexController {
    @GetMapping({"/","index"})
    public String index(){
        return "index";
    }
}

?訪問 localhost:9999

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

到這里可以先去編寫爬蟲,編寫之后,回到這里

⑤編寫Config?

@Configuration
public class ElasticSearchConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1",9200,"http")
                )
        );
        return client;
    }
}

⑥編寫service

因為是爬取的數(shù)據(jù),那么就不走Dao,以下編寫都不會編寫接口,開發(fā)中必須嚴格要求編寫?

ContentService?

@Service
public class ContentService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    // 1、解析數(shù)據(jù)放入 es 索引中
    public Boolean parseContent(String keyword) throws IOException {
        // 獲取內(nèi)容
        List<Content> contents = HtmlParseUtil.parseJD(keyword);
        // 內(nèi)容放入 es 中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m"); // 可更具實際業(yè)務(wù)是指
        for (int i = 0; i < contents.size(); i++) {
            bulkRequest.add(
                    new IndexRequest("jd_goods")
                            .id(""+(i+1))
                            .source(JSON.toJSONString(contents.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        restHighLevelClient.close();
        return !bulk.hasFailures();
    }
        // 2、根據(jù)keyword分頁查詢結(jié)果
    public List<Map<String, Object>> search(String keyword, Integer pageIndex, Integer pageSize) throws IOException {
        if (pageIndex < 0){
            pageIndex = 0;
        }
        SearchRequest jd_goods = new SearchRequest("jd_goods");
        // 創(chuàng)建搜索源建造者對象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 條件采用:精確查詢 通過keyword查字段name
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", keyword);
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));// 60s
        // 分頁
        searchSourceBuilder.from(pageIndex);
        searchSourceBuilder.size(pageSize);
        // 高亮
        // ....
        // 搜索源放入搜索請求中
        jd_goods.source(searchSourceBuilder);
        // 執(zhí)行查詢,返回結(jié)果
        SearchResponse searchResponse = restHighLevelClient.search(jd_goods, RequestOptions.DEFAULT);
        restHighLevelClient.close();
        // 解析結(jié)果
        SearchHits hits = searchResponse.getHits();
        List<Map<String,Object>> results = new ArrayList<>();
        for (SearchHit documentFields : hits.getHits()) {
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            results.add(sourceAsMap);
        }
        // 返回查詢的結(jié)果
        return results;
    }
}

⑦編寫controller

@Controller
public class ContentController {
    @Autowired
    private ContentService contentService;
    @ResponseBody
    @GetMapping("/parse/{keyword}")
    public Boolean parse(@PathVariable("keyword") String keyword) throws IOException {
        return contentService.parseContent(keyword);
    }
    @ResponseBody
    @GetMapping("/search/{keyword}/{pageIndex}/{pageSize}")
    public List<Map<String, Object>> parse(@PathVariable("keyword") String keyword,
                                           @PathVariable("pageIndex") Integer pageIndex,
                                           @PathVariable("pageSize") Integer pageSize) throws IOException {
        return contentService.search(keyword,pageIndex,pageSize);
    }
}

⑧測試結(jié)果

1、解析數(shù)據(jù)放入 es 索引中?

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

根據(jù)keyword分頁查詢結(jié)果

3、爬蟲(jsoup)

數(shù)據(jù)獲?。簲?shù)據(jù)庫、消息隊列、爬蟲、…

①搜索京東搜索頁面,并分析頁面

java - 商品搜索 - 京東

頁面如下

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

?審查頁面元素

頁面列表id:J_goodsList

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

目標元素:img、price、name

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

②爬取數(shù)據(jù)(獲取請求返回的頁面信息,篩選出可用的)

創(chuàng)建HtmlParseUtil,并簡單編寫

public class HtmlParseUtil {
    public static void main(String[] args) throws IOException {
        /// 使用前需要聯(lián)網(wǎng)
        // 請求url
        String url = "http://search.jd.com/search?keyword=java";
        // 1.解析網(wǎng)頁(jsoup 解析返回的對象是瀏覽器Document對象)
        Document document = Jsoup.parse(new URL(url), 30000);
        // 使用document可以使用在js對document的所有操作
        // 2.獲取元素(通過id)
        Element j_goodsList = document.getElementById("J_goodsList");
        // 3.獲取J_goodsList ul 每一個 li
        Elements lis = j_goodsList.getElementsByTag("li");
        // 4.獲取li下的 img、price、name
        for (Element li : lis) {
            String img = li.getElementsByTag("img").eq(0).attr("src");// 獲取li下 第一張圖片
            String name = li.getElementsByClass("p-name").eq(0).text();
            String price = li.getElementsByClass("p-price").eq(0).text();
            System.out.println("=======================");
            System.out.println("img : " + img);
            System.out.println("name : " + name);
            System.out.println("price : " + price);
        }
    }
}

運行結(jié)果

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

一般圖片特別多的網(wǎng)站,所有的圖片都是通過延遲加載的

// 打印標簽內(nèi)容
Elements lis = j_goodsList.getElementsByTag("li");
System.out.println(lis);

?打印所有l(wèi)i標簽,發(fā)現(xiàn)img標簽中并沒有屬性src的設(shè)置,只是data-lazy-ing設(shè)置圖片加載的地址

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

創(chuàng)建HtmlParseUtil、改寫

  • 更改圖片獲取屬性為?data-lazy-img

  • 與實體類結(jié)合,實體類如下

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Content implements Serializable {
    private static final long serialVersionUID = -8049497962627482693L;
    private String name;
    private String img;
    private String price;
}
  • 封裝為方法

public class HtmlParseUtil {
    public static void main(String[] args) throws IOException {
        System.out.println(parseJD("java"));
    }
    public static List<Content> parseJD(String keyword) throws IOException {
        /// 使用前需要聯(lián)網(wǎng)
        // 請求url
        String url = "http://search.jd.com/search?keyword=" + keyword;
        // 1.解析網(wǎng)頁(jsoup 解析返回的對象是瀏覽器Document對象)
        Document document = Jsoup.parse(new URL(url), 30000);
        // 使用document可以使用在js對document的所有操作
        // 2.獲取元素(通過id)
        Element j_goodsList = document.getElementById("J_goodsList");
        // 3.獲取J_goodsList ul 每一個 li
        Elements lis = j_goodsList.getElementsByTag("li");
//        System.out.println(lis);
        // 4.獲取li下的 img、price、name
        // list存儲所有l(wèi)i下的內(nèi)容
        List<Content> contents = new ArrayList<Content>();
        for (Element li : lis) {
            // 由于網(wǎng)站圖片使用懶加載,將src屬性替換為data-lazy-img
            String img = li.getElementsByTag("img").eq(0).attr("data-lazy-img");// 獲取li下 第一張圖片
            String name = li.getElementsByClass("p-name").eq(0).text();
            String price = li.getElementsByClass("p-price").eq(0).text();
            // 封裝為對象
            Content content = new Content(name,img,price);
            // 添加到list中
            contents.add(content);
        }
//        System.out.println(contents);
        // 5.返回 list
        return contents;
    }
}

結(jié)果展示

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

4、搜索高亮

在3、的基礎(chǔ)上添加內(nèi)容

①ContentService

// 3、 在2的基礎(chǔ)上進行高亮查詢
public List<Map<String, Object>> highlightSearch(String keyword, Integer pageIndex, Integer pageSize) throws IOException {
    SearchRequest searchRequest = new SearchRequest("jd_goods");
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    // 精確查詢,添加查詢條件
    TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", keyword);
    searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
    searchSourceBuilder.query(termQueryBuilder);
    // 分頁
    searchSourceBuilder.from(pageIndex);
    searchSourceBuilder.size(pageSize);
    // 高亮 =========
    HighlightBuilder highlightBuilder = new HighlightBuilder();
    highlightBuilder.field("name");
    highlightBuilder.preTags("<span style='color:red'>");
    highlightBuilder.postTags("</span>");
    searchSourceBuilder.highlighter(highlightBuilder);
    // 執(zhí)行查詢
    searchRequest.source(searchSourceBuilder);
    SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
    // 解析結(jié)果 ==========
    SearchHits hits = searchResponse.getHits();
    List<Map<String, Object>> results = new ArrayList<>();
    for (SearchHit documentFields : hits.getHits()) {
        // 使用新的字段值(高亮),覆蓋舊的字段值
        Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
        // 高亮字段
        Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
        HighlightField name = highlightFields.get("name");
        // 替換
        if (name != null){
            Text[] fragments = name.fragments();
            StringBuilder new_name = new StringBuilder();
            for (Text text : fragments) {
                new_name.append(text);
            }
            sourceAsMap.put("name",new_name.toString());
        }
        results.add(sourceAsMap);
    }
    return results;
}

②ContentController

@ResponseBody
@GetMapping("/h_search/{keyword}/{pageIndex}/{pageSize}")
public List<Map<String, Object>> highlightParse(@PathVariable("keyword") String keyword,
                                       @PathVariable("pageIndex") Integer pageIndex,
                                       @PathVariable("pageSize") Integer pageSize) throws IOException {
    return contentService.highlightSearch(keyword,pageIndex,pageSize);
}

③結(jié)果展示

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

5、前后端分離(簡單使用Vue)

刪除Controller 方法上的?@ResponseBody注解

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

①下載并引入Vue.min.js和axios.js

如果安裝了nodejs,可以按如下步驟,沒有的素材里有

打開電腦cmd命令窗口,執(zhí)行以下命令

npm init

npm install vue
npm install axios

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

沒有axios和vue文件的網(wǎng)上下載一個就行,然后復(fù)制到項目里

?【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

②修改靜態(tài)頁面

引入js

<script th:src="@{/js/vue.min.js}"></script>
<script th:src="@{/js/axios.min.js}"></script>

修改后的index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    <title>狂神說Java-ES仿京東實戰(zhàn)</title>
    <link rel="stylesheet" th:href="@{/css/style.css}"/>
    <script th:src="@{/js/jquery.min.js}"></script>
</head>
<body class="pg">
<div class="page">
    <div id="app" class=" mallist tmall- page-not-market ">
        <!-- 頭部搜索 -->
        <div id="header" class=" header-list-app">
            <div class="headerLayout">
                <div class="headerCon ">
                    <!-- Logo-->
                    <h1 id="mallLogo">
                        <img th:src="@{/images/jdlogo.png}" alt="">
                    </h1>
                    <div class="header-extra">
                        <!--搜索-->
                        <div id="mallSearch" class="mall-search">
                            <form name="searchTop" class="mallSearch-form clearfix">
                                <fieldset>
                                    <legend>天貓搜索</legend>
                                    <div class="mallSearch-input clearfix">
                                        <div class="s-combobox" id="s-combobox-685">
                                            <div class="s-combobox-input-wrap">
                                                <input v-model="keyword"  type="text" autocomplete="off" id="mq"
                                                       class="s-combobox-input"  aria-haspopup="true">
                                            </div>
                                        </div>
                                        <button type="submit" @click.prevent="searchKey" id="searchbtn">搜索</button>
                                    </div>
                                </fieldset>
                            </form>
                            <ul class="relKeyTop">
                                <li><a>狂神說Java</a></li>
                                <li><a>狂神說前端</a></li>
                                <li><a>狂神說Linux</a></li>
                                <li><a>狂神說大數(shù)據(jù)</a></li>
                                <li><a>狂神聊理財</a></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 商品詳情頁面 -->
        <div id="content">
            <div class="main">
                <!-- 品牌分類 -->
                <form class="navAttrsForm">
                    <div class="attrs j_NavAttrs" style="display:block">
                        <div class="brandAttr j_nav_brand">
                            <div class="j_Brand attr">
                                <div class="attrKey">
                                    品牌
                                </div>
                                <div class="attrValues">
                                    <ul class="av-collapse row-2">
                                        <li><a href="#"> 狂神說 </a></li>
                                        <li><a href="#"> Java </a></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
                <!-- 排序規(guī)則 -->
                <div class="filter clearfix">
                    <a class="fSort fSort-cur">綜合<i class="f-ico-arrow-d"></i></a>
                    <a class="fSort">人氣<i class="f-ico-arrow-d"></i></a>
                    <a class="fSort">新品<i class="f-ico-arrow-d"></i></a>
                    <a class="fSort">銷量<i class="f-ico-arrow-d"></i></a>
                    <a class="fSort">價格<i class="f-ico-triangle-mt"></i><i class="f-ico-triangle-mb"></i></a>
                </div>
                <!-- 商品詳情 -->
                <div class="view grid-nosku" >
                    <div class="product" v-for="result in results">
                        <div class="product-iWrap">
                            <!--商品封面-->
                            <div class="productImg-wrap">
                                <a class="productImg">
                                    <img :src="result.img">
                                </a>
                            </div>
                            <!--價格-->
                            <p class="productPrice">
                                <em v-text="result.price"></em>
                            </p>
                            <!--標題-->
                            <p class="productTitle">
                                <a v-html="result.name"></a>
                            </p>
                            <!-- 店鋪名 -->
                            <div class="productShop">
                                <span>店鋪: 狂神說Java </span>
                            </div>
                            <!-- 成交信息 -->
                            <p class="productStatus">
                                <span>月成交<em>999筆</em></span>
                                <span>評價 <a>3</a></span>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script th:src="@{/js/vue.min.js}"></script>
<script th:src="@{/js/axios.min.js}"></script>
<script>
    new Vue({
        el:"#app",
        data:{
            "keyword": '', // 搜索的關(guān)鍵字
            "results":[] // 后端返回的結(jié)果
        },
        methods:{
            searchKey(){
                var keyword = this.keyword;
                console.log(keyword);
                axios.get('h_search/'+keyword+'/0/20').then(response=>{
                    console.log(response.data);
                    this.results=response.data;
                })
            }
        }
    });
</script>
</body>
</html>

測試

【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】

使用term(精確查詢)時遇到的問題

字段值必須是一個詞(索引中存在的詞),才能匹配

  • 問題:中文字符串,term查詢時無法查詢到數(shù)據(jù)(比如,“編程”兩字在文檔中存在,但是搜索不到)

  • 原因:索引為配置中文分詞器(默認使用standard,即所有中文字符串都會被切分為單個中文漢字作為單詞),所以沒有超過1個漢字的詞,也就無法匹配,進而查不到數(shù)據(jù)

  • 解決:創(chuàng)建索引時配置中文分詞器,如

PUT example
{
  "mappings": {
    "properties": {
      "name":{
        "type": "text",
        "analyzer": "ik_max_word"  // ik分詞器
      }
    }
  }
}
  • 查詢的英文字符只能是小寫,大寫都無效

  • 查詢時英文單詞必須是完整的

最后附上我自己用的依賴

<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.8.0</version>
</dependency>
<!-- elasticsearch 的客戶端 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency>
<!-- elasticsearch 依賴 2.x 的 log4j -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<!-- junit 單元測試 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>

?結(jié)束!文章來源地址http://www.zghlxwxcb.cn/news/detail-475181.html

到了這里,關(guān)于【SpringBoot整合ElasticSearch7.x及實戰(zhàn)】的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • Elasticsearch7學(xué)習(xí)筆記(尚硅谷)

    Elasticsearch7學(xué)習(xí)筆記(尚硅谷)

    Elasticsearch是一個 實時的分布式搜索和分析引擎 。它可以幫助你用前所未有的速度去處理大規(guī)模數(shù)據(jù)。它可以用于 全文搜索,結(jié)構(gòu)化搜索以及分析 ,當(dāng)然你也可以將這三者進行組合。 Elasticsearch是一個建 立在全文搜索引擎 Apache Lucene? 基礎(chǔ) 上的搜索引擎,可以說Lucene是當(dāng)今

    2024年01月23日
    瀏覽(28)
  • ElasticSearch7.6.x 學(xué)習(xí)筆記

    ElasticSearch7.6.x 學(xué)習(xí)筆記

    ElasticSearch,簡稱es,es是一個 開源 的 高擴展 的 分布式全文檢索引擎 ,它可以近乎實時的存儲、檢索數(shù)據(jù)。且本身擴展性很好,可以擴展到上百臺服務(wù)器,處理PB級別的數(shù)據(jù)。es也使用java開發(fā)并使用Lucene作為核心來實現(xiàn)所用索引和搜索的功能。但是,它的目的是通過簡單的

    2023年04月16日
    瀏覽(23)
  • python使用ElasticSearch7.17.6筆記

    python使用ElasticSearch7.17.6筆記

    數(shù)操作系統(tǒng):windows10 我開始使用最新的版本,8.4.1但是使用過程中kibana啟動不了,就索性使用舊版; 下載地址: es7.17.6 下載地址? kibana7.17.6下載地址 解壓到合適的位置,更改elasticsearch.yml 添加配置如下: 更改kibana.yml配置 到各自的bin目錄下啟動兩個服務(wù)bat文件, 在瀏覽器中

    2024年02月07日
    瀏覽(23)
  • SpringBoot集成Elasticsearch7.x(3)|(aggregations之指標聚合查詢)

    章節(jié) 第一章鏈接: SpringBoot集成Elasticsearch7.x(1)|(增刪改查功能實現(xiàn)) 第二章鏈接: SpringBoot集成Elasticsearch7.x(2)|(復(fù)雜查詢) 第三章鏈接: SpringBoot集成Elasticsearch7.x(3)|(aggregations之指標聚合查詢) 第四章鏈接: SpringBoot集成Elasticsearch7.x(4)|(aggregations之分桶聚合查詢)

    2024年02月05日
    瀏覽(22)
  • Java + SpringBoot 操作 ElasticSearch7.x.x工具類RestHighLevelClientUtils

    ElasticSearch創(chuàng)建索引,刪除索引,判斷 index 是否存在,根據(jù) id 刪除指定索引中的文檔, 根據(jù) id 更新指定索引中的文檔,根據(jù) id 更新指定索引中的文檔,根據(jù)某字段的 k-v 更新索引中的文檔, 添加文檔 手動指定id,簡單模糊匹配 默認分頁為 0,10, term 查詢 精準匹配,term 查詢

    2024年02月13日
    瀏覽(20)
  • springboot集成Elasticsearch7.16,使用https方式連接并忽略SSL證書

    千萬萬苦利用科學(xué)上網(wǎng)找到了,記錄一下

    2024年02月09日
    瀏覽(25)
  • 本地部署Canal筆記-實現(xiàn)MySQL與ElasticSearch7數(shù)據(jù)同步

    本地部署Canal筆記-實現(xiàn)MySQL與ElasticSearch7數(shù)據(jù)同步

    本地搭建canal實現(xiàn)mysql數(shù)據(jù)到es的簡單的數(shù)據(jù)同步,僅供學(xué)習(xí)參考 建議首先熟悉一下canal同步方式:https://github.com/alibaba/canal/wiki 本地搭建MySQL數(shù)據(jù)庫 本地搭建ElasticSearch 本地搭建canal-server 本地搭建canal-adapter 本地環(huán)境為window11,大部分組件采用docker進行部署,MySQL采用8.0.27, 推薦

    2024年02月02日
    瀏覽(96)
  • 【Elasticsearch學(xué)習(xí)筆記五】es常用的JAVA API、es整合SpringBoot項目中使用、利用JAVA代碼操作es、RestHighLevelClient客戶端對象

    目錄 一、Maven項目集成Easticsearch 1)客戶端對象 2)索引操作 3)文檔操作 4)高級查詢 二、springboot項目集成Spring Data操作Elasticsearch 1)pom文件 2)yaml 3)數(shù)據(jù)實體類 4)配置類 5)Dao數(shù)據(jù)訪問對象 6)索引操作 7)文檔操作 8)文檔搜索 三、springboot項目集成bboss操作elasticsearch

    2023年04月09日
    瀏覽(37)
  • Elasticsearch基礎(chǔ),SpringBoot整合Elasticsearch

    Elasticsearch基礎(chǔ),SpringBoot整合Elasticsearch

    Elasticsearch,簡稱為es,es是一個開源的高擴展的分布式全文檢索引擎,它可以近乎實時的存儲、檢索數(shù)據(jù);本身擴展性很好,可以擴展到上百臺服務(wù)器,處理PB級別(大數(shù)據(jù)時代)的數(shù)據(jù)。es也使用Java開發(fā)并使用Lucene作為其核心來實現(xiàn)所有索引和搜索的功能,但是它的目的是通

    2024年01月19日
    瀏覽(20)
  • 圖數(shù)據(jù)庫_Neo4j和SpringBoot整合使用_實戰(zhàn)創(chuàng)建明星關(guān)系圖譜---Neo4j圖數(shù)據(jù)庫工作筆記0010

    2023-09-10 10:37:48 補充 注意:下面是舊版本的語法,如果你發(fā)現(xiàn)@NodeEntity這樣的注解沒有的話可以這樣: 這里就要用@Node 另外如果@StartNode和@EndNode都沒有了,那么說明是用法變了. 關(guān)于最新的用法,在官網(wǎng)有明確的說明和案例,很有用: 下面給出官網(wǎng)的案例:

    2024年02月12日
    瀏覽(23)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包