elasticsearch+element UI el-autocomplete+springboot实现搜索引擎
vue前端代码:
<template>
<el-autocomplete
v-model="name"
:fetch-suggestions="querySearch"
placeholder="请输入名称"
:trigger-on-focus="false">
</el-autocomplete>
</template>
<script>
const axios = require("axios");
export default {
name: 'xixi',
data(){
return{
name: ''
}
},
methods:{
//queryString 为在框中输入的值
//callback 回调函数,将处理好的数据推回
querySearch(queryString, callback) {
var list = [{}];
//调用的后台接口
let url = 'http://localhost:8888/search?key='+queryString;
//从后台获取到对象数组
axios.get( url ).then((response)=>{
console.log(response.data.items)
//在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
for(let i of response.data.items){
i.value = i.name; //将想要展示的数据作为value
}
list = response.data.items;
callback(list);
}).catch((error)=>{
console.log(error);
});
},
handleSelect(item) {
console.log(item);
//do something
}
}
}
</script>
<style scoped>
</style>
-----------------------------------------分割线---------------------------------------------------
后台代码:
项目结构:
CORSConfiguration(解决前后端跨域的问题):
package com.demo.elasticsearch.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo</groupId>
<artifactId>elasticsearch</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>elasticsearch</name>
<description>使用springboot+elasticsearch做一个搜索引擎</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- elasticsearch -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifac