首页 > 解决方案 > prisma 是否支持地理空间查询

问题描述

我发现你现在使用 MySQL 和 PostgreSQL,它们支持地理空间类型,我如何对我的 prisma 实现地理空间查询。

假设我想获得纽约附近的所有活动?

标签: prisma

解决方案


我使用 Prisma 和 MySQL 数据库在我的项目中“实现”了自定义 geoSearch:

您需要能够以编程方式连接到您的数据库。

首先,让我们获取我们的环境变量

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 :这些片段不是抽象的,因此可能需要修改/改进。我只是提供一个解决这个临时问题的方法的例子。


推荐阅读