【发布时间】:2018-12-03 05:37:34
【问题描述】:
我发现你现在使用 MySQL 和 PostgreSQL,并且它们支持地理空间类型,我如何对我的 prisma 实现地理空间查询。
假设我想获取纽约附近的所有活动?
【问题讨论】:
标签: prisma
我发现你现在使用 MySQL 和 PostgreSQL,并且它们支持地理空间类型,我如何对我的 prisma 实现地理空间查询。
假设我想获取纽约附近的所有活动?
【问题讨论】:
标签: prisma
我使用 Prisma 和 MySQL 数据库在我的项目中“实施”了自定义地理搜索:
您需要能够以编程方式连接到您的数据库。
首先,让我们获取我们的env var:
const host = process.env.MYSQL_ENDPOINT;
const user = process.env.MYSQL_ROOT_USERNAME;
const password = process.env.MYSQL_ROOT_PASSWORD;
const database = process.env.PRISMA_SERVICE + "@" + process.env.PRISMA_STAGE;
现在尝试使用包promise-mysql 连接到我们的数据库:
let connection;
try {
//Create a connection to the database;
connection = await mysql.createConnection({
host,
user,
password,
database
});
} catch (e) {
console.error(e);
throw new Error("Could not connect to the Database");
}
需要在你的表中有一个空间列,它也应该有一个空间索引。可以使用这些以编程方式进行(表必须为空):
/**
* Add a spatial column to the table, used for geo-searching
* @param {string} tableName name of the table to alter
* @param {string} columnName name of the spatial column
* @param {string} lonColumnName name of the longitude column
* @param {string} latColumnName name of the latitude column
* @param {object} connection connection to the database
* @return {Promise} result of the table alteration
*/
const addSpatialColumn = async (
tableName,
columnName,
lonColumnName,
latColumnName,
connection
) => {
return connection.query(`
ALTER TABLE
${tableName} ADD ${columnName} POINT AS(
ST_POINTFROMTEXT(
CONCAT(
'POINT(',
${lonColumnName},
' ',
${latColumnName},
')'
)
)
) STORED NOT NULL;`);
};
/**
* Add a spatial index to the table
* @param {string} tableName name of the table
* @param {string} columnName name of the column to create an index on
* @param {object} connection connection to the database
* @return {Promise} result of the index creation
*/
const addSpatialIndex = async (tableName, columnName, connection) => {
return connection.query(
`ALTER TABLE ${tableName} ADD SPATIAL INDEX(${columnName});`
);
};
现在是棘手的部分。由于 Prisma 还没有在这方面给我们灌输,您需要您自己确定您的 sql 查询的参数。
然后您可以进行查询,例如:
const query = `SELECT ${sqlSelect} FROM ${sqlFrom} WHERE
MBRContains(ST_GeomFromText("${polygon}"), GeoPoint) ${sqlWhere} LIMIT
${toSkip},${batchSize}`;
const selectedRows = await connection.query(query);
后记:这些 sn-ps 不是抽象的,因此可能需要修改/改进。我只是提供一个解决这个临时问题的方法的例子。
【讨论】:
Prisma 目前不支持地理查询。您可以将 Prisma 用于大多数查询,并直接查询底层数据库以进行地理空间查询。
当此功能可用时,请按照此功能请求获得通知:https://github.com/prismagraphql/prisma/issues/28
【讨论】: