gpt4 book ai didi

prisma - prisma 是否支持 GeoSpatial 查询

转载 作者:行者123 更新时间:2023-12-04 14:23:21 27 4
gpt4 key购买 nike

我发现您现在使用的是 MySQL 和 PostgreSQL,它们支持地理空间类型,我该如何对我的 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);

Post-scriptum : these snippets are not abstractions and therefore, may need modifications/improvements. I am just providing an example of a way to solve this temporary problem.

关于prisma - prisma 是否支持 GeoSpatial 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51010009/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com