如果您有一个类型为 的字段,也会发生此错误geometry
。在拉入 data.table 之前,您应该SELECT AS
并使用空间方法转换为 WKT。见下文,您知道这Shape
是一个 type 字段geometry
。通过使用空间方法.STAsText()
,它将其转换为众所周知的文本 (WKT) 格式,R 可以更轻松地使用该格式。
library(sf)
library(tidyverse)
query <- "
SELECT company, revenue, address, Shape.STAsText() AS ShapeWKT
FROM businesses_table
"
results <- dbFetch(dbSendQuery(con, query)) %>%
filter(!is.na(ShapeWKT)) %>%
mutate(Shape = st_as_sfc(ShapeWKT)) %>%
select(-ShapeWKT) %>%
st_as_sf()
我构建了一个更复杂的函数,允许您指定数据库连接、表名、字段异常(默认返回除字段中的字段外的所有字段exception
)、用于过滤查询的 WHERE 子句,并指定空间字段名称,因为它因表而异(即,可能是Shape
可能是Geo
等)。
spatial_query <- function(con, tablename,
exception = "",
wherefilter = "",
spatialfieldname = "Shape",
spatial = TRUE){
## Get last element (table name) from explicit table name
tmp <- strsplit(tablename, "[.]")[[1]]
tablename_short <- tmp[length(tmp)]
fields <- dbListFields(con, tablename_short)
if(spatial){
fields_to_grab <- fields[!(fields %in% c(exception, spatialfieldname))]
## TODO adjust query to be responsive to Shape
qstring <- paste0('SELECT ', paste(fields_to_grab, collapse = ", "), ', ', spatialfieldname, '.STAsText() AS ShapeWKT FROM ', tablename, ' ', wherefilter)
cat(paste("Sending following SQL statement:", qstring, "\n", sep = "\n"))
ret <- dbFetch(dbSendQuery(con, qstring)) %>%
filter(!is.na(ShapeWKT)) %>%
mutate(Shape = st_as_sfc(ShapeWKT)) %>%
select(-ShapeWKT) %>%
st_as_sf()
}
else{
fields_to_grab <- fields[!(fields %in% exception)]
qstring <- paste0('SELECT ', paste(fields_to_grab, collapse = ", "),' FROM ', tablename, ' ', wherefilter)
cat(paste("Sending following SQL statement:", qstring, "\n", sep = "\n"))
ret <- dbFetch(dbSendQuery(con, qstring))
}
return(ret)
}