firebase - 在 Firestore 中维护对话数据
问题描述
我正在寻找一种在 Cloud Firestore 中存储对话数据的方法。我是 NoSQL 数据库的新手,因此感谢任何提示。
我的目标如下:我想要一个名为“dialogs”的集合,然后以以下格式(或类似格式)存储不同的对话框
dialogs:[
{
id:1,
dialog: [
{
text: "hello is this a text?",
turn: 0
},
{
text: "yes this is a text",
turn: 1
}
],
},
{
id: 2,
dialog:[
{
text: "is this another text?",
turn: 0
},
{
text: "yes this is another text",
turn: 1
}
]
}
]
我当前在我的网络应用程序中的方法如下所示:
db.collection("dialogs").add({id:1,dialog:[]})
首先,我想知道这样的结构是否可能(它不一定是这种结构)。
其次,是否可以生成唯一的 id,然后查询特定的 id?
编辑:我想出了这种方法
const docRef = db.collection("dialogs").doc();
const dialog = {
dialogId: docRef.id,
intent: "SYMPTOM_INFORMATION",
utterance: this.userInput,
state: [],
issuer: "USER",
turn: 0
};
docRef.add(dialog)
我现在不清楚的是我如何用相同的方式查询所有文档dialogId
解决方案
Cloud Firestore 允许您在文档中存储多种数据类型。您可能需要查看以下文档。这将取决于您的用例和需求,但例如,您可以让您的数据库结构看起来像这样:
let data = {
numberExample: 1,
objectExample: {
stringExample: "is this another text?",
numberExample: 1
}
};
let setDoc = db.collection('dialogs').doc('SET_YOUR_DOCUMENT_ID').set(data);
请注意,当您用于set()
创建文档时,您必须指定要创建的文档的 ID。另一方面,要为给定文档自动生成 ID,您必须使用该add()
方法,如文档中所建议的那样。
编辑1:
查询集合中满足相同条件的所有dialog
文档:dialogs
id
let dialogsRef = db.collection('dialogs');
let query = dialogsRef.where('id', '==', '1').get()
.then(snapshot => {
if (snapshot.empty) {
console.log('No matching documents.');
return;
}
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
// TODO: do something with the data.
});
})
.catch(err => {
console.log('Error getting documents', err);
});
要查询集合中的所有dialog
文档及其id
字段:dialogs
let dialogsRef = db.collection('dialogs');
let allDialogs = dialogsRef.get()
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
// TODO: do something with the data.
});
})
.catch(err => {
console.log('Error getting documents', err);
});
更多信息可以在文档中找到。
推荐阅读
- python - PyPi 拒绝版本值
- c++ - 在 `ifstream::getline` 中禁用 Ctrl-Z 行为
- html - 我如何更改两个项目而只将鼠标悬停在一个上
- vue.js - Nuxt:如何显式命名 JS 块?
- c - 使用二分查找查找已排序字符串中的第一个大写字母
- arrays - 尝试在 hlsl 中分配值时我做错了什么?
- javascript - 为 read-more-react npm 包创建 index.d.ts
- ansible - Ansible 处理程序不起作用,除非我包括:它们在我的游戏中?
- c++ - RegisterHotKey() 未检测到按键
- sql-server - 更新 2 个表以将它们与存储过程连接起来