【问题标题】:Save Image in Elasticsearch with Ruby使用 Ruby 在 Elasticsearch 中保存图像
【发布时间】:2015-11-20 22:38:44
【问题描述】:

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

【问题讨论】:

  • 曾经有一个plugin,虽然很久没更新了,似乎只支持到ES v1.3。
  • 插件叫什么名字?
  • 你可以点击链接:)

标签: ruby elasticsearch sinatra


【解决方案1】:

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”

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

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    相关资源
    最近更新 更多