我正在使用这个:
{
bool_vector <- c(TRUE,FALSE)
date_vector <- as.Date(c("2020-05-31","2020-06-30","2020-07-31") )
str_vector <- c("string1","string2")
}
{
bool_function<-function(bool_vector) {
bool_json <- ifelse(length(tolower(as.character(bool_vector))) %in% 2,
'{ "$in" : [ true, false ] }',tolower(as.character(bool_vector)
)
)
# as the field is named bool, the search vector should be bool_vector
bool_field <- gsub("(.*)_.*","\\1",quote(bool_vector) )
bool_json2 <- paste0('"',bool_field,'":',bool_json)
return(bool_json2)
}
date_function<- function(date_vector) {
# as the field is named date, the search vector should be date_vector
date_field <- gsub("(.*)_.*","\\1",quote(date_vector) )
date_json <- paste0('"',date_field,'":{"$gt":{"$date":"'
,min(date_vector),'T00:00:00Z"},"$lt":{"$date":"'
,max(date_vector),'T23:59:59Z"}}'
)
return(date_json)
}
str_function<-function(str_vector) {
# as the field is named str, the search vector should be str_vector
str_field <- gsub("(.*)_.*","\\1",quote(str_vector) )
str_json <- paste0("\"",paste0(str_vector,collapse= "\",\""),"\"")
str_json_2 <- paste0('"',str_field,'":{"$in" : [',str_json,'] }')
return(str_json_2)
}
}
vec_list <- mget(ls(pattern = "vector"))
make_query <- function(vec_list) {
json_list<-list()
i=0
for(vec in vec_list){
i = i+1
if(class(vec)=="logical"){
json_list[[i]] <-bool_function(vec)
} else if (class(vec)=="character") {
json_list[[i]] <- str_function(vec)
} else if (class(vec)=="Date") {
json_list[[i]] <- date_function(vec)
}
}
query <- paste0("{",paste0(unlist(json_list),collapse = ","),"}")
return(query)
}
make_query(vec_list)
"{\"bool\":{ \"$in\" : [ true, false ] },\"date\":{\"$gt\":{\"$date\":\"2020-05-31T00:00:00Z\"},\"$lt\":{\"$date\":\"2020-07-31T23:59:59Z\"}},\"str\":{\"$in\" : [\"string1\",\"string2\"] }}"