Last active
August 29, 2015 14:14
-
-
Save paneq/c6d9f0e71015926e7419 to your computer and use it in GitHub Desktop.
elastic search category filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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