Skip to content

Commit

Permalink
Merge 92794b3 into e517f1d
Browse files Browse the repository at this point in the history
  • Loading branch information
JPrevost committed Feb 13, 2024
2 parents e517f1d + 92794b3 commit 1020405
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
25 changes: 25 additions & 0 deletions app/models/opensearch.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,34 @@ def matches
match_single_field_nested(:subjects, m)

match_geodistance(m) if @params[:geodistance].present?
match_geobox(m) if @params[:geobox].present?
m
end

# https://opensearch.org/docs/latest/query-dsl/geo-and-xy/geo-bounding-box/
def match_geobox(match_array)
match_array << {
bool: {
must: {
match_all: {}
},
filter: {
geo_bounding_box: {
'locations.geoshape': {
top: @params[:geobox][:max_latitude],
bottom: @params[:geobox][:min_latitude],
left: @params[:geobox][:min_longitude],
right: @params[:geobox][:max_longitude]
}
}
}
}
}
end

# https://www.elastic.co/guide/en/elasticsearch/reference/7.17/query-dsl-geo-distance-query.html
# Note: at the time of this implementation, opensearch does not have documentation on
# this features hence the link to the prefork elasticsearch docs
def match_geodistance(match_array)
match_array << {
bool: {
Expand Down
29 changes: 29 additions & 0 deletions test/models/opensearch_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,8 @@ class OpensearchTest < ActiveSupport::TestCase
os.instance_variable_set(:@params,
{ geodistance: { latitude: '42.361145', longitude: '-71.057083', distance: '50mi' } })

refute(os.matches.to_json.include?('{"multi_match":{"query":'))

assert(
os.query.to_json.include?('{"distance":"50mi","locations.geoshape":{"lat":"42.361145","lon":"-71.057083"}}')
)
Expand All @@ -296,4 +298,31 @@ class OpensearchTest < ActiveSupport::TestCase
os.query.to_json.include?('{"distance":"50mi","locations.geoshape":{"lat":"42.361145","lon":"-71.057083"}}')
)
end

test 'can search by bounding box' do
os = Opensearch.new
os.instance_variable_set(:@params,
{ geobox: { max_latitude: '42.886', min_latitude: '41.239',
max_longitude: '-73.928', min_longitude: '-69.507' } })

refute(os.matches.to_json.include?('{"multi_match":{"query"'))

assert(
os.query.to_json.include?('{"locations.geoshape":{"top":"42.886","bottom":"41.239","left":"-69.507","right":"-73.928"}}')
)
end

test 'can search by bounding box and keyword' do
os = Opensearch.new
os.instance_variable_set(:@params,
{ geobox: { max_latitude: '42.886', min_latitude: '41.239',
max_longitude: '-73.928', min_longitude: '-69.507' },
q: 'rail stations' })

assert(os.matches.to_json.include?('{"multi_match":{"query":"rail stations","fields":'))

assert(
os.query.to_json.include?('{"locations.geoshape":{"top":"42.886","bottom":"41.239","left":"-69.507","right":"-73.928"}}')
)
end
end

0 comments on commit 1020405

Please sign in to comment.