当前位置: 首页 > news >正文

在 Elasticsearch 中使用用户行为分析:使用 UBI 和 search-ui 创建一个应用程序

作者:来自 Elastic Eduard Martin 及 Alexander Dávila

通过一个实际示例学习如何在 Elasticsearch 中使用 UBI。我们将创建一个在搜索和点击结果时生成 UBI 事件的应用程序。

想要获得 Elastic 认证吗?看看下一次 Elasticsearch Engineer 培训什么时候开始!

Elasticsearch 拥有丰富的新功能,能帮助你为自己的用例构建最佳的搜索解决方案。深入了解我们的示例笔记本,开始免费云试用,或者现在就在本地机器上尝试 Elastic。


在本文中,我们将创建一个示例应用来收集用户行为数据,展示如何将 UBI 扩展集成到 search-ui 中。我们还将自定义收集的数据,以展示 UBI 标准的灵活性,以及它如何满足不同的需求。

这个示例应用是一个简单的图书搜索引擎,目标是能够捕捉用户的事件,并基于他们的行为(如搜索和点击)将其索引到 Elasticsearch 中。

需求

这个应用需要在 Elasticsearch 中安装 UBI 插件。你可以阅读我们的博客文章获取更多信息。

加载示例数据

我们需要先在 Elasticsearch 中准备一些数据。在 Kibana DevTools Console 中运行以下命令来加载一组产品列表,以便在我们的 UI 中展示。这将创建一个名为 “books” 的新索引,用于本示例。

POST /_bulk
{ "index" : { "_index" : "books" } }
{"name": "Snow Crash", "author": "Neal Stephenson", "release_date": "1992-06-01", "page_count": 470, "price": 14.99, "url": "https://www.amazon.com/Snow-Crash-Neal-Stephenson/dp/0553380958/", "image_url": "https://m.media-amazon.com/images/I/81p4Y+0HzbL._SY522_.jpg" }
{ "index" : { "_index" : "books" } }
{"name": "Revelation Space", "author": "Alastair Reynolds", "release_date": "2000-03-15", "page_count": 585, "price": 16.99, "url": "https://www.amazon.com/Revelation-Space-Alastair-Reynolds/dp/0441009425/", "image_url": "https://m.media-amazon.com/images/I/61nC2ExeTvL._SY522_.jpg"}
{ "index" : { "_index" : "books" } }
{"name": "1984", "author": "George Orwell", "release_date": "1985-06-01", "page_count": 328, "price": 12.99, "url": "https://www.amazon.com/1984-Signet-Classics-George-Orwell/dp/0451524934/", "image_url": "https://m.media-amazon.com/images/I/71rpa1-kyvL._SY522_.jpg"}
{ "index" : { "_index" : "books" } }
{"name": "Fahrenheit 451", "author": "Ray Bradbury", "release_date": "1953-10-15", "page_count": 227, "price": 11.99, "url": "https://www.amazon.com/Fahrenheit-451-Ray-Bradbury/dp/1451673310/", "image_url": "https://m.media-amazon.com/images/I/61sKsbPb5GL._SY522_.jpg"}
{ "index" : { "_index" : "books" } }
{"name": "Brave New World", "author": "Aldous Huxley", "release_date": "1932-06-01", "page_count": 268, "price": 12.99, "url": "https://www.amazon.com/Brave-New-World-Aldous-Huxley/dp/0060850523/", "image_url": "https://m.media-amazon.com/images/I/71GNqqXuN3L._SY522_.jpg"}
{ "index" : { "_index" : "books" } }
{"name": "The Handmaid's Tale", "author": "Margaret Atwood", "release_date": "1985-06-01", "page_count": 311, "price": 13.99, "url": "https://www.amazon.com/Handmaids-Tale-Margaret-Atwood/dp/038549081X/", "image_url": "https://m.media-amazon.com/images/I/61su39k8NUL._SY522_.jpg"}

创建示例应用程序

我们将使用 search-ui 创建一个 UI 应用程序,将 UBI 事件发送到 Elasticsearch。search-ui 是 Elastic 的 JavaScript 库,用于使用内置的 React 组件创建 UI。

Search UI 是 Elastic 基于 React 的框架,用于构建搜索应用程序。它为搜索体验中的所有关键部分提供组件 —— 例如搜索栏、分面、分页和自动建议。自定义其行为(包括添加 UBI)非常简单。

Elasticsearch 连接器

首先,我们需要安装 Elasticsearch 连接器,步骤参考连接器教程。

1)从 GitHub 下载 search-ui 启动应用:

curl https://codeload.github.com/elastic/app-search-reference-ui-react/tar.gz/master | tar -xz

2)进入新目录 app-search-reference-ui-react-main 并安装依赖项:

cd app-search-reference-ui-react-main
npm install

3)通过 npm 包管理器安装 Elasticsearch 连接器:

npm install @elastic/search-ui-elasticsearch-connector

后端服务器

为了遵循最佳实践并确保对 Elasticsearch 的调用通过中间层服务完成,我们来创建一个后端来调用我们的连接器:

1)我们先创建一个新目录和一个新的 JavaScript 文件:

mkdir server
touch server/index.js

2)在新的 index.js 文件中,写入:

import express from "express";
import ElasticsearchAPIConnector from "@elastic/search-ui-elasticsearch-connector";
import { Client } from "@elastic/elasticsearch";
import "dotenv/config";const app = express();
app.use(express.json());const connector = new ElasticsearchAPIConnector({host: process.env.ELASTICSEARCH_HOST,index: process.env.ELASTICSEARCH_INDEX,apiKey: process.env.ELASTICSEARCH_API_KEY
});const esClient = new Client({node: process.env.ELASTICSEARCH_HOST,auth: {apiKey: process.env.ELASTICSEARCH_API_KEY,},
});app.post("/api/search", async (req, res) => {const { state, queryConfig } = req.body;const response = await connector.onSearch(state, queryConfig);res.json(response);
});app.post("/api/autocomplete", async (req, res) => {const { state, queryConfig } = req.body;const response = await connector.onAutocomplete(state, queryConfig);res.json(response);
});app.post("/api/analytics", async (req, res, next) => {try {console.log(`Sending analytics for query_id: ${req.body.query_id}`)req.body.client_id = clientId;await esClient.index({index: "ubi_events",body: req.body,});console.log(req.body);res.status(200).json({ message: "Analytics event saved successfully" });} catch (error) {next(error);}
});app.listen(3001);

通过此更改,我们将默认行为(从浏览器调用 Elasticsearch)替换为调用我们的后端。这种方法更适合生产环境。

在文件末尾,将 export default function 替换为以下定义:

export default function App() {return (<SearchProvider config={config}><Layoutheader={<SearchBox autocompleteSuggestions={false} />}bodyContent={<ResultstitleField={"author"}urlField={"url"}thumbnailField={"image_url"}shouldTrackClickThrough={true}/>}/></SearchProvider>);
}

这将允许我们显示图书的图片,并提供可点击的链接。

要查看完整教程,请访问此文档。

按照步骤操作后,你将得到一个客户端的 index.js 文件和一个服务器端的 server/index.js 相关文件。

配置连接器

我们将配置 onSearch 和 onResultClick 处理程序来设置 UBI query_id。然后,在执行搜索和点击结果时发送 UBI 事件。

配置 onSearch:拦截搜索请求,为每个请求使用 UUID v4 分配一个唯一的 requestId,然后将请求传递给处理链中的下一个处理程序。我们将使用此 ID 作为 UBI query_id,用于将搜索和点击分组。

进入 server/index.js 文件,并扩展连接器以配置 onSearch 方法:

const clientId = uuidv4(); // to maintain a constant client id
class UBIConnector extends ElasticsearchAPIConnector {async onSearch(requestState, queryConfig) {const result = await super.onSearch(requestState, queryConfig);result.requestId = uuidv4();result.clientId = clientId;return result;}
}

之后,声明连接器并自定义搜索请求,通过 ext.ubi 搜索参数将生成的 ID 发送到 UBI 插件。

const connector = new UBIConnector({host: process.env.ELASTICSEARCH_HOST,index: process.env.ELASTICSEARCH_INDEX,apiKey: process.env.ELASTICSEARCH_API_KEY,},(requestBody, requestState, queryConfig) => {requestBody.ext = {ubi: {query_id: requestState.requestId,client_id: requestState.clientId || clientId,user_query: requestState.searchTerm || "",},};if (!requestState.searchTerm) return requestBody;requestBody.query = {multi_match: {query: requestState.searchTerm,fields: Object.keys(queryConfig.search_fields),},};return requestBody;}
);

别忘了添加新的导入。此外,由于我们的前端运行在 localhost:3000,而后端运行在 localhost:3001,它们被视为不同的源。‘源’ 由协议、域名和端口的组合定义,所以即使它们都在同一主机上并使用 HTTP 协议,不同的端口也会使它们成为不同的源,因此我们需要 CORS。要了解更多关于 CORS 的信息,请访问本指南。

import cors from "cors";
import { v4 as uuidv4 } from "uuid";
...
app.use(cors({origin: "http://localhost:3000", // Your React app URLcredentials: true
}));

进入客户端的 client/App.js 文件(点击以打开完整的完成文件)。

在 config 对象声明中添加 onResultClick 事件处理程序,每当用户点击搜索结果时,将分析数据发送到后端,捕获的信息包括查询 ID、结果详情以及用户交互的具体信息,如点击的文档属性、文档位置和页码。在这里,你还可以添加用户同意共享的其他信息。确保遵守隐私法律(例如欧洲的 GDPR)。

const config = {apiConnector: connector,
onResultClick: async (r) => {const locationData = await getLocationData();const payload = {application: "search-ui",action_name: "click",query_id: r.requestId || "",client_id: r.clientId || "",timestamp: new Date().toISOString(),message_type: "CLICK_THROUGH",message: `Clicked ${r.result.name.raw}`,user_query: r.query,event_attributes: {object: {device: getDeviceType(),object_id: r.result.id.raw,description: `${r.result.name.raw}(${r.result.release_date.raw}) by ${r.result.author.raw}`,position: {ordinal: r.resultIndexOnPage,page_depth: r.page,},user: {ip: locationData.ip,city: locationData.city,region: locationData.region,country: locationData.country,location: {lat:locationData.latitude,lon:locationData.longitude}}},},};fetch(`http://localhost:3001/api/analytics`, {method: "POST",headers: {"Content-Type": "application/json",},body: JSON.stringify(payload),}).then((r) => console.log(r)).catch((error) => {console.error("Error:", error);});}// other Search UI config options
};

SearchUI 参考中的完整事件钩子可以在这里找到

接下来,修改 search_fields 和 result_fields 以与数据集对齐。我们将通过图书的名称和作者进行搜索,并返回名称、作者、image_url、url 和价格。

const config = {
...searchQuery: {search_fields: {name: {},author: {},},result_fields: {name: { raw: {} },author: { raw: {} },image_url: { raw: {} },url: { raw: {} },price: { raw: {} },release_date: { raw: {} }},},
};

最后,我们将添加几个辅助函数来定义设备类型和用户数据:

const getDeviceType = () => {const userAgent = navigator.userAgent.toLowerCase();if (/tablet|ipad|playbook|silk/.test(userAgent)) {return 'tablet';}if (/mobile|iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/.test(userAgent)) {return 'mobile';}return 'desktop';
};const getLocationData = async () => {const response = await fetch('https://ipapi.co/json/');const data = await response.json();return {ip: data.ip,city: data.city,region: data.region,country: data.country_name,latitude: data.latitude,longitude: data.longitude};
};

其余的 config 对象可以保持不变。

我们整理了一个仓库,你可以在这里找到。它包含了更完整的项目版本。可以通过以下命令克隆:

git clone https://github.com/llermaly/search-ui-ubi.git

如果你使用 GitHub 仓库,需要为服务器提供以下环境变量:

ELASTICSEARCH_HOST=your_elasticsearch_url
ELASTICSEARCH_API_KEY=your_api_key
ELASTICSEARCH_INDEX=books

运行应用程序

现在你可以启动服务器:

cd server
npm install && node index.js

如果遇到与该库相关的错误,可能需要单独安装 CORS:

npm install cors

在另一个终端中:

cd client
npm install && npm start

然后在浏览器中访问 http://localhost:3000。

最终效果将如下所示:

在 Elasticsearch 端,我们可以为 ubi_events 索引创建一个(相当简单的)映射,以便将用户位置作为位置处理:

PUT ubi_events
{"mappings": {"properties": {"event_attributes.object.user.location": {"type": "geo_point"}}}
}

每次搜索时,会生成一个 ubi_queries 事件,而在点击时,会生成一个类型为 click 的 ubi_events。

这就是一个 ubi_queries 事件的样子:

{"_index": "ubi_queries","_id": "aCXqW5gB87F1AivbVvHI","_score": null,"_ignored": ["query.keyword"],"_source": {"query_response_id": "a8aca3d9-1cbc-4800-8853-fd1889172b9b","user_query": "snow","query_id": "d198c517-7d3b-49dd-be11-f573728d578e","query_response_object_ids": ["0","6"],"query": """{"from":0,"size":20,"query":{"multi_match":{"query":"snow","fields":["author^1.0","name^1.0"]}},"_source":{"includes":["name","author","image_url","url","price","release_date"],"excludes":[]},"sort":[{"_score":{"order":"desc"}}],"ext":{"query_id":"d198c517-7d3b-49dd-be11-f573728d578e","user_query":"snow","client_id":"8a5de3a1-7a1b-47ed-b64f-5be0537829be","object_id_field":null,"query_attributes":{}}}""","query_attributes": {},"client_id": "8a5de3a1-7a1b-47ed-b64f-5be0537829be","timestamp": 1753888741063},"sort": [1753888741063]}

这是一个示例 ubi_events 文档:

{"_index": "ubi_events","_id": "fiDqW5gBftHcGY9PXtao","_score": null,"_source": {"application": "search-ui","action_name": "click","query_id": "3850340e-0e72-4f20-a06e-27a52d983b39","client_id": "8a5de3a1-7a1b-47ed-b64f-5be0537829be","timestamp": "2025-07-30T15:19:02.659Z","message_type": "CLICK_THROUGH","message": "Clicked Snow Crash","user_query": "snow","event_attributes": {"object": {"device": "desktop","object_id": "vrFBK5gBZjU2lCOmiNSX","description": "Snow Crash(1992-06-01) by Neal Stephenson","position": {"ordinal": 0,"page_depth": 1},"user": {"ip": "2800:bf0:108:18:d5ca:fa84:416f:99e0","city": "Quito","region": "Pichincha","country": "Ecuador","location": {"lat": -0.2309,"lon": -78.5211}}}}},"sort": [1753888742659]}

从这里,我们已经可以看到有用的信息,比如与特定查询相关的操作。

结论

将 search-ui 与 UBI 扩展集成是一个可以收集用户行为的宝贵见解的过程,并可以通过其他元数据扩展,例如用户位置和设备类型。这些信息会自动索引到两个独立的索引中,分别用于查询和操作,并可以通过唯一 ID 关联。这些信息使开发者能够更好地理解用户如何使用应用,并优先处理可能影响用户体验的问题。

原文:Using UBI in Elasticsearch: Creating an app with UBI and search-ui - Elasticsearch Labs

http://www.dtcms.com/a/362906.html

相关文章:

  • 【序列晋升】25 Spring Cloud Open Service Broker 如何为云原生「服务市集」架桥铺路?
  • 【JavaScript】前端两种路由模式,Hash路由,History 路由
  • UBUNTU之Onvif开源服务器onvif_srvd:2、测试
  • @Value注解底层原理(二)
  • 云端职达:你的AI求职专属猎头,颠覆传统招聘模式
  • 哈尔滨云前沿服务器托管与租用服务
  • STM32——串口
  • 在windows上使用ROS2 kilted
  • Pytorch Yolov11目标检测+window部署+推理封装 留贴记录
  • LeetCode算法日记 - Day 30: K 个一组翻转链表、两数之和
  • Unity核心概率④:MonoBehavior
  • @Hadoop 介绍部署使用详细指南
  • 从 WPF 到 Avalonia 的迁移系列实战篇6:ControlTheme 和 Style区别
  • R 语言科研绘图第 71 期 --- 散点图-边际
  • 小白也能看懂!“找不到 msvcp140.dll无法继续执行代码” 的6种简易解决方法,5 分钟快速修复
  • Watt Toolkit下载安装并加速GitHub
  • C# 原型模式(C#中的克隆)
  • 基因表达数据的K-M生存曲线的数据处理及绘制
  • Anaconda安装与使用详细教程
  • 服务器CPU飙高?排查步骤与工具推荐
  • 深入探索 HarmonyOS Stage 模型与 ArkUI:构建现代化、高性能应用
  • 【NestJS】HTTP 接口传参的 5 种方式(含前端调用与后端接收)
  • 面试新纪元:无声胜有声,让AI成为你颈上的智慧伙伴
  • 基于YOLO8的番茄成熟度检测系统(数据集+源码+文章)
  • 利用飞算Java打造电商系统核心功能模块的设计与实现
  • Controller返回CompletableFuture到底是怎么样的
  • 【DSP28335 入门教程】定时器中断:为你的系统注入精准的“心跳”
  • 在windows平台oracle 23ai 数据库上使用bbed
  • zephyr设备树的硬件描述转换为c语言
  • 梳理一下 @types/xxx