Skip to content

Instantly share code, notes, and snippets.

@paneq
Last active August 29, 2015 14:14
Show Gist options
  • Save paneq/c6d9f0e71015926e7419 to your computer and use it in GitHub Desktop.
Save paneq/c6d9f0e71015926e7419 to your computer and use it in GitHub Desktop.
elastic search category filter
client = Elasticsearch::Client.new host: 'localhost:9200', logger: Rails.logger
client.indices.create({
index: "businesses",
body: {
settings: {},
mappings: {
"business" => {
properties:{
name: {:type=>"string", index: "not_analyzed"}, # you probably need different index type depending on what kind of queries there are
category: {:type=>"string", index: "not_analyzed"},
}
}
}
}
})
# reindex
Business.select("id, name, category").find_each do |b|
client.index index: 'businesses', type: 'businesses', id: u.id, body: {
name: b.name,
category: b.category,
}
end
# search
search = client.search({
index: 'businesses',
body: {
query: {
filtered: {
query: {
query_string: {query: params["query"]}
},
filter: {
term: { # 'terms' if you need multiple categories (OR query)
category: params["category"]
}
}
}
},
from: params["from"] || 0,
size: params["size"]
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment