已解决
基于ElasticSearch+Vue实现简易搜索
来自网友在路上 156856提问 提问时间:2023-10-26 04:36:59阅读次数: 56
最佳答案 问答题库568位专家为你答疑解惑
基于ElasticSearch+Vue实现简易搜索
一、模拟数据
二、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 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!