当前位置:首页 > 编程笔记 > 正文
已解决

基于ElasticSearch+Vue实现简易搜索

来自网友在路上 156856提问 提问时间:2023-10-26 04:36:59阅读次数: 56

最佳答案 问答题库568位专家为你答疑解惑

基于ElasticSearch+Vue实现简易搜索

一、模拟数据

产品名称描述价格库存数量品牌名称智能手表智能手表,具有健康跟踪和通知功能。199.991000TechWatch4K智能电视4K分辨率智能电视,提供出色的画质。699.99500VisionTech无线耳机降噪无线耳机,提供高品质音频体验。149.99800AudioMasters笔记本电脑高性能笔记本电脑,配备快速处理器。999.99300TechLaptops数码相机高分辨率数码相机,支持多种拍摄模式。449.99200PhotoPro便携式充电器便携式充电器,为移动设备提供电力。29.992000PowerBoost无线路由器高速无线路由器,适用于大型网络。79.99400NetSpeed游戏机游戏机,支持多种游戏和娱乐功能。399.99100GameZone手机壳手机壳,适用于各种手机型号。19.991500PhoneGuard运动鞋高性能运动鞋,适用于各种运动。79.99800SportsTech4K超高清显示器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="https://unpkg.com/element-ui/lib/theme-chalk/index.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="https://unpkg.com/vue@2/dist/vue.js"></script>
<!-- Import Element UI -->
<script src="https://unpkg.com/element-ui/lib/index.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>

四、效果图

在这里插入图片描述
在这里插入图片描述

查看全文

99%的人还看了

相似问题

猜你感兴趣

版权申明

本文"基于ElasticSearch+Vue实现简易搜索":http://eshow365.cn/6-24777-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!