Initialization steps:

        1. Prepare elasticsearch connection, including details for indexing.
422076
def initialize(self, conf, ctx):
        
        config = get_config()['ElasticsearchIndexBolt']
        elasticsearch_class = import_name(config['elasticsearch_class'])
        self.es = elasticsearch_class(**config['elasticsearch_init'])
        self.index = config['index']
        self.doc_type = config['doc_type']
721081
def ensure_index(self, index, mappings=None, settings=None, clear=False):
        
        mappings = mappings or []
        if isinstance(mappings, dict):
            mappings = [mappings]
        exists = self.indices.exists_index(index)
        if exists and not mappings and not clear:
            return
        if exists and clear:
            self.indices.delete_index(index)
            exists = False

        if exists:
            if not mappings:
                self.indices.delete_index(index)
                self.indices.refresh()
                self.indices.create_index(index, settings)
                return

            if clear:
                for maps in mappings:
                    for key in list(maps.keys()):
                        self.indices.delete_mapping(index, doc_type=key)
                self.indices.refresh()
            if isinstance(mappings, SettingsBuilder):
                for name, data in list(mappings.mappings.items()):
                    self.indices.put_mapping(doc_type=name, mapping=data, indices=index)

            else:
                from pyes.mappings import DocumentObjectField, ObjectField

                for maps in mappings:
                    if isinstance(maps, tuple):
                        name, mapping = maps
                        self.indices.put_mapping(doc_type=name, mapping=mapping, indices=index)
                    elif isinstance(maps, dict):
                        for name, data in list(maps.items()):
                            self.indices.put_mapping(doc_type=name, mapping=maps, indices=index)
                    elif isinstance(maps, (DocumentObjectField, ObjectField)):
                        self.put_mapping(doc_type=maps.name, mapping=maps.as_dict(), indices=index)

                return

        if settings:
            if isinstance(settings, dict):
                settings = SettingsBuilder(settings, mappings)
        else:
            if isinstance(mappings, SettingsBuilder):
                settings = mappings
            else:
                settings = SettingsBuilder(mappings=mappings)
        if not exists:
            self.indices.create_index(index, settings)
            self.indices.refresh(index, timesleep=1)
988928
void initResultIndex() {

        int startIndex = 0;
        if ((m_pageIndex > 0) && (m_pageSize > 0)) {
            startIndex = (m_pageIndex - 1) * m_pageSize;
        }

        m_resultIndex = startIndex > m_resultSize ? m_resultSize : startIndex;
    }
220822
def get_elasticsearch_info():
    """"""
    from elasticsearch import (
        Elasticsearch,
        ConnectionError as ESConnectionError
    )
    if hasattr(settings, 'ELASTICSEARCH_URL'):
        url = settings.ELASTICSEARCH_URL
    else:
        return {"status": NO_CONFIG}
    start = datetime.now()
    try:
        search = Elasticsearch(url, request_timeout=TIMEOUT_SECONDS)
        search.info()
    except ESConnectionError:
        return {"status": DOWN}
    del search  # The elasticsearch library has no "close" or "disconnect."
    micro = (datetime.now() - start).microseconds
    return {
        "status": UP, "response_microseconds": micro,
    }
911008
private void initialize(long index) {
    currentSegment = journal.getSegment(index);
    currentSegment.acquire();
    currentReader = currentSegment.createReader();
    long nextIndex = getNextIndex();
    while (index > nextIndex && hasNext()) {
      next();
      nextIndex = getNextIndex();
    }
  }
29841
protected void initSearchIndexes() {

        I_CmsSearchIndex index = null;
        for (int i = 0, n = m_indexes.size(); i < n; i++) {
            index = m_indexes.get(i);
            // reset disabled flag
            index.setEnabled(true);
            // check if the index has been configured correctly
            if (index.checkConfiguration(m_adminCms)) {
                // the index is configured correctly
                try {
                    index.initialize();
                } catch (Exception e) {
                    if (CmsLog.INIT.isWarnEnabled()) {
                        // in this case the index will be disabled
                        CmsLog.INIT.warn(Messages.get().getBundle().key(Messages.INIT_SEARCH_INIT_FAILED_1, index), e);
                    }
                }
            }
            // output a log message if the index was successfully configured or not
            if (CmsLog.INIT.isInfoEnabled()) {
                if (index.isEnabled()) {
                    CmsLog.INIT.info(
                        Messages.get().getBundle().key(Messages.INIT_INDEX_CONFIGURED_2, index, index.getProject()));
                } else {
                    CmsLog.INIT.warn(
                        Messages.get().getBundle().key(
                            Messages.INIT_INDEX_NOT_CONFIGURED_2,
                            index,
                            index.getProject()));
                }
            }
        }
    }
1217980
def SetIndexName(self, index_name):
    
    self._index_name = index_name
    logger.debug('Elasticsearch index name: {0:s}'.format(index_name))
217850
def create_connection(self, alias='default', **kwargs):
        
        kwargs.setdefault('serializer', serializer)
        conn = self._conns[alias] = Elasticsearch(**kwargs)
        return conn
190868
def init_db_conn(connection_name, HOSTS=None):
    
    el = elasticsearch.Elasticsearch(hosts=HOSTS)
    el_pool.connections[connection_name] = ElasticSearchClient(el)
973324
def __init(self):
        
        params = {
            "f" : "json"
        }
        json_dict = self._get(url=self._currentURL,
                                 param_dict=params,
                                 securityHandler=self._securityHandler,
                                 proxy_url=self._proxy_url,
                                 proxy_port=self._proxy_port)
        self._json = json.dumps(json_dict)
        self._json_dict = json_dict
        attributes = [attr for attr in dir(self)
                    if not attr.startswith('__') and \
                    not attr.startswith('_')]
        for k,v in json_dict.items():
            if k.lower() == "extensions":
                self._extensions = []
                for ext in v:
                    self._extensions.append(Extension.fromJSON(ext))
                    del ext
            elif k in attributes:
                setattr(self, "_"+ k, json_dict[k])
            else:
                print( k, " - attribute not implemented in manageags.AGSService.")
            del k
            del v
720622
public void createIndex(String index, boolean ignoreErrors, String indexSettings) throws IOException {
        logger.debug("create index [{}]", index);
        logger.trace("index settings: [{}]", indexSettings);
        CreateIndexRequest cir = new CreateIndexRequest(index);
        if (!isNullOrEmpty(indexSettings)) {
            cir.source(indexSettings, XContentType.JSON);
        }
        try {
            client.indices().create(cir, RequestOptions.DEFAULT);
        } catch (ElasticsearchStatusException e) {
            if (e.getMessage().contains("resource_already_exists_exception") && !ignoreErrors) {
                throw new RuntimeException("index already exists");
            }
            if (!e.getMessage().contains("resource_already_exists_exception")) {
                throw e;
            }
        }
        waitForHealthyIndex(index);
    }
1025617
private void init() throws IndexerException {
		if (!loaded) {
			loaded = true;

			String storageType = config.getString(null, "storage", "type");
			try {
				storage = PluginManager.getStorage(storageType);
				storage.init(config.toString());
			} catch (PluginException pe) {
				throw new IndexerException(pe);
			}

			// Credentials
			usernameMap = new HashMap<String, String>();
			passwordMap = new HashMap<String, String>();

			solr = initCore("solr");
			anotar = initCore("anotar");

			// initialise non-hardcoded indexers
			solrServerMap = new HashMap<String, SolrServer>();
			JsonObject indexerConfig = config.getObject("indexer");

			List<String> hardcodedValues = Arrays.asList("type", "properties", "useCache", "buffer", "solr", "anotar");
			for (Object key : indexerConfig.keySet()) {
				if (key instanceof String) {
					String keyString = (String) key;
					if (!hardcodedValues.contains(keyString)) {
						solrServerMap.put(keyString, initCore(keyString));
					}
				}
			}

			anotarAutoCommit = config.getBoolean(true, "indexer", "anotar", "autocommit");
			propertiesId = config.getString(DEFAULT_METADATA_PAYLOAD, "indexer", "propertiesId");

			customParams = new HashMap<String, String>();

			// Caching
			scriptCache = new HashMap<String, PyObject>();
			groovyScriptCache = new HashMap<String, String>();
			configCache = new HashMap<String, JsonSimpleConfig>();
			useCache = config.getBoolean(true, "indexer", "useCache");

		}
		loaded = true;
	}
656566
def create_index(index):
    """"""
    logger.info("Creating search index: '%s'", index)
    client = get_client()
    return client.indices.create(index=index, body=get_index_mapping(index))
887412
def _prepare_connection(**kwargs):
    '''
    
    '''
    init_args = {}
    fun_kwargs = {}
    netmiko_kwargs = __salt__['config.get']('netmiko', {})
    netmiko_kwargs.update(kwargs)  # merge the CLI args with the opts/pillar
    netmiko_init_args, _, _, netmiko_defaults = inspect.getargspec(BaseConnection.__init__)
    check_self = netmiko_init_args.pop(0)
    for karg, warg in six.iteritems(netmiko_kwargs):
        if karg not in netmiko_init_args:
            if warg is not None:
                fun_kwargs[karg] = warg
            continue
        if warg is not None:
            init_args[karg] = warg
    conn = ConnectHandler(**init_args)
    return conn, fun_kwargs
33730
def index(models=None, name=None, force=False, keep=False):
    '''
    
    '''
    index_name = name or default_index_name()

    doc_types_names = [m.__name__.lower() for m in adapter_catalog.keys()]
    models = [model.lower().rstrip('s') for model in (models or [])]
    for model in models:
        if model not in doc_types_names:
            log.error('Unknown model %s', model)
            sys.exit(-1)

    log.info('Initiliazing index "{0}"'.format(index_name))
    if es.indices.exists(index_name):
        if IS_TTY and not force:
            msg = 'Index {0} will be deleted, are you sure?'
            click.confirm(msg.format(index_name), abort=True)
        es.indices.delete(index_name)

    es.initialize(index_name)

    with handle_error(index_name, keep):

        disable_refresh(index_name)
        for adapter in iter_adapters():
            if not models or adapter.doc_type().lower() in models:
                index_model(index_name, adapter)
            else:
                log.info('Copying {0} objects to the new index'.format(
                         adapter.model.__name__))
                # Need upgrade to Elasticsearch-py 5.0.0 to write:
                # es.reindex({
                #     'source': {'index': es.index_name, 'type': adapter.doc_type()},
                #     'dest': {'index': index_name}
                # })
                #
                # http://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.reindex
                # This method (introduced in Elasticsearch 2.3 but only in Elasticsearch-py 5.0.0)
                # triggers a server-side documents copy.
                # Instead we use this helper for meant for backward compatibility
                # but with poor performance as copy is client-side (scan+bulk)
                es_reindex(es.client, es.index_name, index_name, scan_kwargs={
                    'doc_type': adapter.doc_type()
                })

        enable_refresh(index_name)
    # At this step, we don't want error handler to delete the index
    # in case of error
    set_alias(index_name, delete=not keep)
1228015
def initialize(self):
        ''''''
        if es.indices.exists(self.index_name):
            es.indices.put_mapping(index=self.index_name, doc_type=DOCTYPE, body=MAPPING)
        else:
            es.indices.create(self.index_name, {
                'mappings': {'advice': MAPPING},
                'settings': {'analysis': ANALSYS},
            })
45139
protected function initializeSolrConnection()
    {
        $solr = GeneralUtility::makeInstance(ConnectionManager::class)->getConnectionByPageId($this->page->id, $this->page->sys_language_uid);

        // do not continue if no server is available
        if (!$solr->getWriteService()->ping()) {
            throw new \Exception(
                'No Solr instance available while trying to index a page.',
                1234790825
            );
        }

        $this->solrConnection = $solr;
    }