从 r 中的 Search() elastic 创建的数据框,但在使用结果数据框时收到错误“conn 必须是弹性连接对象”

Data frame created from Search() elastic in r, but receiving error 'conn must be an elastic connection object when using resulting dataframe

我在R中使用elastic包,Elasticsearch版本号“6.8.3”,elastic pkg的版本是“1.0.0”。我有一个基于关键字输入列表搜索弹性的功能,输出是 hits$hits 的数据框。然后这个数据框被用于另一个函数,该函数进行数据操作并绘制图表。

但是,当我在数据操作函数中使用生成的数据帧时,运行在数据操作函数的某个部分甚至没有提到弹性时,我一直收到此错误: Error: 'conn' must be an elastic connection object; see ?connect

这里是弹性函数:

keyword_search <- function(file) {
  library(elastic)
  library(readxl)
  library(rjson)
  library(magrittr)

  con <- connect(host = '10.0.53.250', port = 9200)

#file is an excel file with "keyword" in the first cell of the first column, #then one search term per cell going down the column
  the_terms <- read_excel(file)
  the_terms %>%
    na.omit() %>%
    as.list()
  r <- data.frame()

  for (t in the_terms$keyword) {
    print(t)
    result <- Search(con, index="cars", body = paste0('{"query": {"match_phrase" : {"body_":', '"', t, '"', '}}}'), asdf = TRUE, size = 5000)
    r <- rbind(r, result$hits$hits)
  }
icars <- r
return(icars)
}

数据操作函数:

wordcloud_table  <- function(icars) {

  library(wordcloud2)
  library(dplyr)
  library(readxl)
  library(tidytext)
  library(wordcloud)
  library(tidyr)
  data(stop_words)
  source('stemmer.R')

  custom_stopwords <- c('1', '2', '3', '4', '5', '6', '7', '8', '9', '0',  'hey', 'hehe')

  custom_stopwords_df <- tibble(word = custom_stopwords)

  clean_cars_df <- icars %>% 
    dplyr::select(report_name, body_)

  tidy_cars<- clean_cars_df %>%
    unnest_tokens(word, body_)

  stopwords_df<- tibble(word = stopwords())

  tidy_cars <- tidy_cars %>%
    anti_join(stopwords_df)

  tidy_cars <- tidy_cars %>%
    anti_join(stop_words)

  tidy_cars <- tidy_cars %>%
    anti_join(custom_stopwords_df)

  wordcountdata <- tidy_cars %>% count(word)

  forwordcloud <- as.data.frame(wordcountdata)
  return(forwordcloud)
}

那我运行

icars <- keyword_search("keywords_onecol.xlsx")

wordcloud_table(icars)

每次我在wordcloud函数中代码到达wordcountdata <- tidy_cars %>% count(word)时就得到'conn连接对象错误,我不明白为什么,因为那个函数中没有conn,这也很随机让它挂在代码的那部分而不是第一次使用 tidy_cars。希望有人能帮我解决这个问题,我很茫然...

这是回溯:

12.
stop("'conn' must be an elastic connection object; see ?connect", 
    call. = FALSE) 
11.
is_conn(conn) 
10.
count(., word) 
9.
function_list[[k]](value) 
8.
withVisible(function_list[[k]](value)) 
7.
freduce(value, `_function_list`) 
6.
`_fseq`(`_lhs`) 
5.
eval(quote(`_fseq`(`_lhs`)), env, env) 
4.
eval(quote(`_fseq`(`_lhs`)), env, env) 
3.
withVisible(eval(quote(`_fseq`(`_lhs`)), env, env)) 
2.
tidy_cars %>% count(word) 
1.
wordcloud_table(icars) 

您的函数名称有冲突:elastic::countdplyr::count。如果加载了两个包,则一个包会覆盖另一个包的同名 fxn。您可以通过为所有函数命名空间来最轻松地修复,因此只需将 count() 更改为 dplyr::count (我假设您正在尝试使用 dplyr 的计数)