基于ElasticSearch+Vue实现简易搜索

编程入门 行业动态 更新时间:2024-10-26 10:37:38

基于ElasticSearch+Vue实现<a href=https://www.elefans.com/category/jswz/34/1769136.html style=简易搜索"/>

基于ElasticSearch+Vue实现简易搜索

基于ElasticSearch+Vue实现简易搜索

一、模拟数据

产品名称描述价格库存数量品牌名称
智能手表智能手表,具有健康跟踪和通知功能。199.991000TechWatch
4K智能电视4K分辨率智能电视,提供出色的画质。699.99500VisionTech
无线耳机降噪无线耳机,提供高品质音频体验。149.99800AudioMasters
笔记本电脑高性能笔记本电脑,配备快速处理器。999.99300TechLaptops
数码相机高分辨率数码相机,支持多种拍摄模式。449.99200PhotoPro
便携式充电器便携式充电器,为移动设备提供电力。29.992000PowerBoost
无线路由器高速无线路由器,适用于大型网络。79.99400NetSpeed
游戏机游戏机,支持多种游戏和娱乐功能。399.99100GameZone
手机壳手机壳,适用于各种手机型号。19.991500PhoneGuard
运动鞋高性能运动鞋,适用于各种运动。79.99800SportsTech
4K超高清显示器4K超高清显示器,提供卓越的图像质量。599.99150UltraView
智能家居设备智能家居设备,实现智能化家居控制。249.99300SmartLiving

二、python导入脚本

# coding=gbk
import pandas as pd
from elasticsearch import Elasticsearch
from elasticsearch.helpers import streaming_bulk# 连接到Elasticsearch
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])# 检查是否成功连接
if es.ping():print("Connected to Elasticsearch")
else:print("Failed to connect to Elasticsearch")# 读取Excel文件
data = pd.read_excel('demoData.xls')# 将DataFrame转换为字典格式
documents = data.to_dict(orient='records')# 逐个文档导入数据到Elasticsearch
success, failed = 0, 0
total_documents = len(documents)
for doc in documents:index_action = {'_index': 'ecommerce',  # 修改为你的索引名称'_id': doc['产品名称'],  # 使用产品名称作为文档ID'_source': doc}try:result = next(streaming_bulk(es, [index_action], index=index_action['_index']))success += 1except Exception as e:print(f"Failed to index document {index_action['_id']}: {e}")failed += 1print(f'Successfully indexed {success} documents, failed to index {failed} documents.')

三、vue代码

<!DOCTYPE html>
<html><head><meta charset="UTF-8"><!-- Import CSS --><link rel="stylesheet" href=".css"><style>* {margin: 0;padding: 0;}body {background-image: linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%);}/* 添加上边距样式 */.card-container {margin-top: 20px;}/* 设置高亮文字颜色为红色 */.highlight-text em {color: red;}/* 样式用于显示产品信息字段 */.product-info {margin-top: 10px;font-weight: bold;}</style>
</head><body><div id="app" style="width: 80%; margin: 0 auto; margin-top: 20px;"><h3>基于ElasticSearch+Vue实现简易搜索</h3><el-input v-model="content" placeholder="请输入内容" @input="searchProducts"></el-input><br><br><hr><!-- 显示搜索结果 --><div id="searchResults"><el-card v-for="result in searchResults" :key="result._id" class="card-container"><div slot="header"><strong v-html="result.highlightedProductName" class="highlight-text"></strong></div><div class="product-info">产品名称: {{ result.productName }}</div><div class="product-info">描述: {{ result.productDescription }}</div><div class="product-info">价格: {{ result.productPrice }}</div><div class="product-info">库存数量: {{ result.productStock }}</div><div class="product-info">品牌名称: {{ result.productBrand }}</div></el-card></div></div>
</body>
<!-- Import Vue before Element -->
<script src="@2/dist/vue.js"></script>
<!-- Import Element UI -->
<script src=".js"></script>
<script>new Vue({el: '#app',data: function () {return {content: "",searchResults: []}},methods: {searchProducts: function () {// 构建Elasticsearch查询const query = {query: {match: {"产品名称": this.content  // 使用正确的字段名}},highlight: {fields: {"产品名称": {}  // 高亮 "产品名称" 字段}}};// 发起HTTP请求搜索文档fetch("http://localhost:9200/ecommerce/_search", {method: "POST",headers: {"Content-Type": "application/json"},body: JSON.stringify(query)}).then(response => response.json()).then(data => {this.displaySearchResults(data);}).catch(error => {console.error("Error:", error);});},displaySearchResults: function (response) {this.searchResults = response.hits.hits.map(function (hit) {return {highlightedProductName: hit.highlight["产品名称"][0],  // 使用正确的字段名productName: hit._source.产品名称,  // 使用正确的字段名productDescription: hit._source.描述,  // 使用正确的字段名productPrice: hit._source.价格,  // 使用正确的字段名productStock: hit._source.库存数量,  // 使用正确的字段名productBrand: hit._source.品牌名称,  // 使用正确的字段名_id: hit._id};});}}})
</script></html>

四、效果图


更多推荐

基于ElasticSearch+Vue实现简易搜索

本文发布于:2023-12-05 08:24:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1663661.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:简易   ElasticSearch   Vue

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!