Skip to content

Instantly share code, notes, and snippets.

@ewlarson
Last active August 31, 2017 05:49
Show Gist options
  • Save ewlarson/10e66a31cdb31a29cae15961b745eb0d to your computer and use it in GitHub Desktop.
Save ewlarson/10e66a31cdb31a29cae15961b745eb0d to your computer and use it in GitHub Desktop.
Calculate centroid for Solr RPT field value
# Install Dependences
require 'rsolr'
# Connect to solr
solr = RSolr.connect :url => 'http://localhost:8983/solr/geoportal'
# Search request
response = solr.get 'select', :params => {:q => '*:*', :rows => '10000'}
response["response"]["docs"].each_with_index do |doc, index|
begin
puts "#{doc['uuid']} / #{doc['solr_geom'].to_s}"
geom_field = doc['solr_geom'].to_s
exp = /^\s*ENVELOPE\(
\s*([-\.\d]+)\s*,
\s*([-\.\d]+)\s*,
\s*([-\.\d]+)\s*,
\s*([-\.\d]+)\s*
\)\s*$/x # uses 'x' option for free-spacing mode
bbox_match = exp.match(geom_field)
return geom_field unless bbox_match # return as-is, not a WKT
w, e, n, s = bbox_match.captures
puts bbox_match.inspect
# West and East
# Calculate average
lng = [w.to_f,e.to_f]
lng = lng.inject{|sum,el| sum + el}.to_f / lng.size
# North and South
# Calculate average
lat = [s.to_f,n.to_f]
lat = lat.inject{|sum,el| sum + el}.to_f / lat.size
# Centroid in Solr is lat,lng
centroid = [lat,lng]
centroid = centroid.join(",")
puts centroid.inspect
# GEOM Field
doc['centroid_geom'] = centroid
# String Field
doc['centroid_s'] = centroid
# String with docValues (_sdv) added GBL schema
doc['uuid_sdv'] = doc['uuid']
doc['dc_title_sdv'] = doc['dc_title_s']
doc['centroid_sdv'] = centroid
doc['bbox_sdv'] = "#{w},#{e},#{n},#{s}"
# Remove "score" from hash before re-indexing
doc.delete("score")
#Add Doc
solr.add(doc)
#Committing each doc
# This is silly, but also helps to check for bbox/centroid errors
solr.commit({softCommit: true})
rescue
puts "BBox or centroid no good - #{doc['uuid']}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment