ruby 有没有一种方法可以在ElasticSearch或Tire中计算索引的所有元素?

8iwquhpp  于 2023-03-22  发布在  Ruby
关注(0)|答案(8)|浏览(122)

如果能有一个元素的计数,而不必像这样进行搜索,那就太好了

Obj.search("id:*").count

这可能吗?

up9lanfz

up9lanfz1#

在ElasticSearch中,您可以使用count API对所有元素进行计数

curl -XGET http://localhost:9200/index/_count

参见他们网站上的Count API文档。

nzkunb0c

nzkunb0c2#

首先,你应该使用match_all查询:MyModel.search( { query { all } }).results.total。(在Lucene中,请不惜一切代价避免通配符查询。)
目前,Tire没有公开“count”API。这将改变。

5tmbdcev

5tmbdcev3#

刚刚从Karmi得到一个提示。计数API现在可用。
您可以执行以下操作:

s = Tire.search 'articles-test', :search_type => 'count' do
  query { term :tags, 'ruby' }
end

只有这样s.results.total才被定义。
参见此处:https://github.com/karmi/tire/blob/master/test/integration/count_test.rb

gopyfrb3

gopyfrb34#

如果你正在使用gem 'elasticsearch-model',这里有一个很好的一行代码:

Elasticsearch::Model.client.count(index: 'your_index_name_here')['count']
slsn1g29

slsn1g295#

从控制台:

Model.search("*:*").results.total

也许能帮助别人)

axr492tv

axr492tv6#

您也可以在elasticsearch-model gem中执行此操作:

Article.search("cats", search_type: 'count').results.total
# => 2026

你不会引起一个球...

Article.search("cats", search_type: 'count').map {|r| r.title}
# => []
llew8vvj

llew8vvj7#

如果你想得到索引中的文档数量,你也可以只检查index stats,像这样:

curl -XGET localhost:9200/_stats

在结果中,您将获得文档/已删除文档的数量(尚未合并的文档)。

alen0pnh

alen0pnh8#

当我使用MyModel.search(query: { match_all: {} }).results.total时,我收到的最大计数是10000,这是“index.max_result_window”设置的默认值。因此,我不相信这是正确的答案。
相反,我的解决方案是利用count API,在Ruby中看起来像这样:

Elasticsearch::Model.client.count(index: MyModel.index_name)['count']

相关问题