-
Notifications
You must be signed in to change notification settings - Fork 88
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add support to create index with mapping definition #89
Changes from all commits
8d59b1d
9306290
7dd00fe
85b1cfc
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -23,6 +23,7 @@ | |
import logging | ||
import hashlib | ||
import types | ||
import json | ||
|
||
|
||
class InvalidSettingsException(Exception): | ||
|
@@ -88,6 +89,10 @@ def from_crawler(cls, crawler): | |
|
||
cls.validate_settings(ext.settings) | ||
ext.es = cls.init_es_client(crawler.settings) | ||
|
||
if 'ELASTICSEARCH_INDEX_MAPPING' in ext.settings: | ||
cls.create_index_with_mapping(cls, ext) | ||
|
||
return ext | ||
|
||
def process_unique_key(self, unique_key): | ||
|
@@ -158,3 +163,25 @@ def close_spider(self, spider): | |
if len(self.items_buffer): | ||
self.send_items() | ||
|
||
def create_index_with_mapping(self, ext): | ||
index_name = self.create_index_name(ext) | ||
mapping_file = ext.settings['ELASTICSEARCH_INDEX_MAPPING'] | ||
|
||
if ext.es.indices.exists(index_name): | ||
logging.debug("index already exists, mapping will not be updated") | ||
else: | ||
logging.debug("will create index with mapping definition") | ||
file = open(mapping_file, "r") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. use a ctx manager to close the file right after 😉 |
||
mapping_data = json.loads(file.read()) | ||
ext.es.indices.create( | ||
index=index_name, ignore=400, body=mapping_data) | ||
|
||
def create_index_name(ext): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not mandatory but I would extrapolate from |
||
index_name = ext.settings['ELASTICSEARCH_INDEX'] | ||
index_suffix_format = ext.settings['ELASTICSEARCH_INDEX_DATE_FORMAT'] | ||
|
||
if index_suffix_format: | ||
dt = datetime.now() | ||
index_name += "-" + datetime.strftime(dt, index_suffix_format) | ||
|
||
return index_name |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
not an expert on this tool yet but seems a good place to do it (right after ES init)