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

标签 ruby elasticsearch sinatra

我正在使用 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/

相关文章:

ruby - 梯形面上推拉后出现圆圈

ruby - 更惯用的 Ruby 写法是什么?

ruby - 按顺序运行 rake 任务

rubyzip Zip::ZipFile.open_buffer 需要一个 String 类或 IO 类的参数

elasticsearch - 3个字母后在Elastic Search中自动建议

elasticsearch - Elasticsearch Date字段的默认值

elasticsearch - 如何使用Elasticsearch过滤查询结果

ruby - Sinatra Synchrony 与 Redis 连接池

ruby - 如何访问 sinatra 错误处理程序中响应的 HTTP 代码?

ruby - 在 Sinatra(ruby web 框架)中我只想执行一次的代码放在哪里?