gpt4 book ai didi

ruby - 使用 Ruby 在 Elasticsearch 中保存图像

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:05 25 4
gpt4 key购买 nike

我正在使用 Elasticsearch 作为我的 Ruby/Sinatra 应用程序的数据存储,我想保存图像。有没有办法将图像作为二进制文件索引到 ES 中?如果是这样,我应该如何着手执行此操作,然后将二进制文件转换回图像以便在网站上显示它?

最佳答案

Elasticsearch 可以使用二进制类型存储二进制数据。二进制类型需要进行base64编码,默认不会被索引。这是一个 es 映射的例子

POST http://localhost:9200/adimages/
{
"mappings" : {
"images" : {
"properties" : {
"image" : { "type" : "binary"},
"id" : {"type" : "string"}
}
}
}

一些sinatra/ruby代码

  get '/pictures/:name' do |name|                                                                                                                                                    
@image = @es_client.search index: 'adsimages', body: { query: { match: { id: name } } }
@image = AdHelpers.get_hashie_list(@image)
content_type 'image/png' #hardcoded content type for now
fileContent = Base64.decode64(@image[0].image);
end

post '/sell/pictures' do
#adsimagesindex/images
image_id = SecureRandom.hex
file = params[:file][:tempfile] #get the post from body
fileContent = file.read
fileContent = Base64.encode64(fileContent)
@es_client.index index: 'adsimages', type: 'images', id: image_id, body: {id: image_id, image: fileContent}
redirect '/ads/sell/pictures'
end

然后您使用表单提交图像

<form class="form-horizontal" action="/ads/sell/pictures" method="post">
<div class="container">
<div class="form-group">
<label for="upload-pictures">Upload Pictures</label>
<input type="file" id="file" name="upload-pictures[]" multiple>
</div>

<button type="submit" class="btn btn-default">Next</button>
</div>
</form>

要检索图像,请执行“GET/ads/sell/pictures/7a911a0355ad1cc3cfc78bbf6038699b” obligatory lena

如果您想将图像与文档一起存储(取决于您的用例),您可以在搜索时通过指定要返回的字段来省略图像字段。或者,您可以只将图像 ID 与文档一起存储,并仅为图像创建索引。

希望这对您有所帮助!

关于ruby - 使用 Ruby 在 Elasticsearch 中保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32234258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com