Create a elasticSearch linked to the object
779544
public function createMapping()
    {
        $index = $this->client->getIndex($this->indexName);
        $type = $index->getType(self::INDEX_TYPE);

        $mappingProperties = array(
            'id' => array('type' => 'string', 'include_in_all' => true),
            'elementId' => array('type' => 'string', 'include_in_all' => true),
            'nodeId' => array('type' => 'string', 'include_in_all' => true),
            'siteId' => array('type' => 'string', 'include_in_all' => true),
            'language' => array('type' => 'string', 'include_in_all' => true),
            'name' => array('type' => 'string', 'include_in_all' => true),
            'updatedAt' => array('type' => 'long', 'include_in_all' => false),
            'blocks' => array('properties' => array(
                'content' => array('type' => 'string',  'store' => true),
                'type' => array('type' => 'string', 'store' => true)
            )),
        );

        $mapping = $this->mappingFactory->create($type);
        $mapping->setProperties($mappingProperties);

        $mapping->send();
    }
1302732
def _attach_obj(self, req, obj):
        """"""

        # Attach the object to the request
        json.dump(obj, req)

        # Also set the content-type header
        req['content-type'] = self._content_type
1087647
def _set_object_self(self, obj):
        
        from nefertari.elasticsearch import ES
        location = self.request.path_url
        route_kwargs = {}

        """ Check for parents """
        if self.request.matchdict:
            route_kwargs.update(self.request.matchdict)
        try:
            type_, obj_pk = obj['_type'], obj['_pk']
        except KeyError:
            return
        resource = (self.model_collections.get(type_) or
                    self.model_collections.get(ES.src2type(type_)))
        if resource is not None:
            route_kwargs.update({resource.id_name: obj_pk})
            location = self.request.route_url(
                resource.uid, **route_kwargs)
        obj.setdefault('_self', location)
998654
def create_index(index_name, **kwargs):
    
    es = elasticsearch.Elasticsearch(**kwargs)
    es.indices.create(index=index_name, body=mapping)
    return connect(index_name, **kwargs)
343758
def get_objects(self, search_field, search_val):
        """"""
        query = ("{ size: " + str(self.max_hits) + ", " +
                 "query: { filtered: { filter: { " +
                 search_field + ": { value: \"" + search_val + "\"" +
                 " } } } } } }")
        self.connect_es()
        res = self.es.search(index=self.index, body=query)
        # self.pr_dbg("%d Hits:" % res['hits']['total'])
        objects = {}
        for doc in res['hits']['hits']:
            objects[doc['_id']] = {}
            # To make uploading easier in the future:
            # Record all those bits into the backup.
            # Mimics how ES returns the result.
            # Prevents having to store this in some external, contrived, format
            objects[doc['_id']]['_index'] = self.index  # also in doc['_index']
            objects[doc['_id']]['_type'] = doc['_type']
            objects[doc['_id']]['_id'] = doc['_id']
            objects[doc['_id']]['_source'] = doc['_source']  # the actual result
        return objects
888350
function( object, propertyTable, eid ) {

		// Create a new BST for this entity for by-value matching
		if (this.indexVal[eid] === undefined)
			this.indexVal[eid] = new BinarySearchTree({
				compareKeys: objectBstComparison,
				checkValueEquality: objectBstEquals,
				unique: true,
			});

		// Keep object references
		var nid = this.indexRef.length;
		this.indexVal[eid].insert( propertyTable, nid );
		this.indexRef.push( object );

		// Keep ID on the object itself so we have a faster lookup,
		// and do it in a non-enumerable property so it doesn't pollute the objects.
		Object.defineProperty(
			object, "__iref__", {
				enumerable: false,
				value: nid,
			}
		);

	}
927405
function buildSearch (opts) {
  // eslint-disable-next-line no-unused-vars
  const { makeRequest, ConfigurationError, handleError, snakeCaseKeys } = opts
  /**
   * Perform a [search](http://www.elastic.co/guide/en/elasticsearch/reference/master/search-search.html) request
   *
   * @param {list} index - A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices
   * @param {list} type - A comma-separated list of document types to search; leave empty to perform the operation on all types
   * @param {string} analyzer - The analyzer to use for the query string
   * @param {boolean} analyze_wildcard - Specify whether wildcard and prefix queries should be analyzed (default: false)
   * @param {boolean} ccs_minimize_roundtrips - Indicates whether network round-trips should be minimized as part of cross-cluster search requests execution
   * @param {enum} default_operator - The default operator for query string query (AND or OR)
   * @param {string} df - The field to use as default where no field prefix is given in the query string
   * @param {boolean} explain - Specify whether to return detailed information about score computation as part of a hit
   * @param {list} stored_fields - A comma-separated list of stored fields to return as part of a hit
   * @param {list} docvalue_fields - A comma-separated list of fields to return as the docvalue representation of a field for each hit
   * @param {number} from - Starting offset (default: 0)
   * @param {boolean} ignore_unavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
   * @param {boolean} ignore_throttled - Whether specified concrete, expanded or aliased indices should be ignored when throttled
   * @param {boolean} allow_no_indices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
   * @param {enum} expand_wildcards - Whether to expand wildcard expression to concrete indices that are open, closed or both.
   * @param {boolean} lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored
   * @param {string} preference - Specify the node or shard the operation should be performed on (default: random)
   * @param {string} q - Query in the Lucene query string syntax
   * @param {list} routing - A comma-separated list of specific routing values
   * @param {time} scroll - Specify how long a consistent view of the index should be maintained for scrolled search
   * @param {enum} search_type - Search operation type
   * @param {number} size - Number of hits to return (default: 10)
   * @param {list} sort - A comma-separated list of <field>:<direction> pairs
   * @param {list} _source - True or false to return the _source field or not, or a list of fields to return
   * @param {list} _source_excludes - A list of fields to exclude from the returned _source field
   * @param {list} _source_includes - A list of fields to extract and return from the _source field
   * @param {number} terminate_after - The maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early.
   * @param {list} stats - Specific 'tag' of the request for logging and statistical purposes
   * @param {string} suggest_field - Specify which field to use for suggestions
   * @param {enum} suggest_mode - Specify suggest mode
   * @param {number} suggest_size - How many suggestions to return in response
   * @param {string} suggest_text - The source text for which the suggestions should be returned
   * @param {time} timeout - Explicit operation timeout
   * @param {boolean} track_scores - Whether to calculate and return scores even if they are not used for sorting
   * @param {boolean} track_total_hits - Indicate if the number of documents that match the query should be tracked
   * @param {boolean} allow_partial_search_results - Indicate if an error should be returned if there is a partial search failure or timeout
   * @param {boolean} typed_keys - Specify whether aggregation and suggester names should be prefixed by their respective types in the response
   * @param {boolean} version - Specify whether to return document version as part of a hit
   * @param {boolean} seq_no_primary_term - Specify whether to return sequence number and primary term of the last modification of each hit
   * @param {boolean} request_cache - Specify if request cache should be used for this request or not, defaults to index level setting
   * @param {number} batched_reduce_size - The number of shard results that should be reduced at once on the coordinating node. This value should be used as a protection mechanism to reduce the memory overhead per search request if the potential number of shards in the request can be large.
   * @param {number} max_concurrent_shard_requests - The number of concurrent shard requests per node this search executes concurrently. This value should be used to limit the impact of the search on the cluster in order to limit the number of concurrent shard requests
   * @param {number} pre_filter_shard_size - A threshold that enforces a pre-filter roundtrip to prefilter search shards based on query rewriting if the number of shards the search request expands to exceeds the threshold. This filter roundtrip can limit the number of shards significantly if for instance a shard can not match any documents based on it's rewrite method ie. if date filters are mandatory to match but the shard bounds and the query are disjoint.
   * @param {boolean} rest_total_hits_as_int - Indicates whether hits.total should be rendered as an integer or an object in the rest search response
   * @param {object} body - The search definition using the Query DSL
   */

  const acceptedQuerystring = [
    'analyzer',
    'analyze_wildcard',
    'ccs_minimize_roundtrips',
    'default_operator',
    'df',
    'explain',
    'stored_fields',
    'docvalue_fields',
    'from',
    'ignore_unavailable',
    'ignore_throttled',
    'allow_no_indices',
    'expand_wildcards',
    'lenient',
    'preference',
    'q',
    'routing',
    'scroll',
    'search_type',
    'size',
    'sort',
    '_source',
    '_source_excludes',
    '_source_includes',
    'terminate_after',
    'stats',
    'suggest_field',
    'suggest_mode',
    'suggest_size',
    'suggest_text',
    'timeout',
    'track_scores',
    'track_total_hits',
    'allow_partial_search_results',
    'typed_keys',
    'version',
    'seq_no_primary_term',
    'request_cache',
    'batched_reduce_size',
    'max_concurrent_shard_requests',
    'pre_filter_shard_size',
    'rest_total_hits_as_int',
    'pretty',
    'human',
    'error_trace',
    'source',
    'filter_path'
  ]

  const snakeCase = {
    analyzeWildcard: 'analyze_wildcard',
    ccsMinimizeRoundtrips: 'ccs_minimize_roundtrips',
    defaultOperator: 'default_operator',
    storedFields: 'stored_fields',
    docvalueFields: 'docvalue_fields',
    ignoreUnavailable: 'ignore_unavailable',
    ignoreThrottled: 'ignore_throttled',
    allowNoIndices: 'allow_no_indices',
    expandWildcards: 'expand_wildcards',
    searchType: 'search_type',
    _sourceExcludes: '_source_excludes',
    _sourceIncludes: '_source_includes',
    terminateAfter: 'terminate_after',
    suggestField: 'suggest_field',
    suggestMode: 'suggest_mode',
    suggestSize: 'suggest_size',
    suggestText: 'suggest_text',
    trackScores: 'track_scores',
    trackTotalHits: 'track_total_hits',
    allowPartialSearchResults: 'allow_partial_search_results',
    typedKeys: 'typed_keys',
    seqNoPrimaryTerm: 'seq_no_primary_term',
    requestCache: 'request_cache',
    batchedReduceSize: 'batched_reduce_size',
    maxConcurrentShardRequests: 'max_concurrent_shard_requests',
    preFilterShardSize: 'pre_filter_shard_size',
    restTotalHitsAsInt: 'rest_total_hits_as_int',
    errorTrace: 'error_trace',
    filterPath: 'filter_path'
  }

  return function search (params, options, callback) {
    options = options || {}
    if (typeof options === 'function') {
      callback = options
      options = {}
    }
    if (typeof params === 'function' || params == null) {
      callback = params
      params = {}
      options = {}
    }

    // check required url components
    if (params['type'] != null && (params['index'] == null)) {
      const err = new ConfigurationError('Missing required parameter of the url: index')
      return handleError(err, callback)
    }

    // validate headers object
    if (options.headers != null && typeof options.headers !== 'object') {
      const err = new ConfigurationError(`Headers should be an object, instead got: ${typeof options.headers}`)
      return handleError(err, callback)
    }

    var warnings = []
    var { method, body, index, type, ...querystring } = params
    querystring = snakeCaseKeys(acceptedQuerystring, snakeCase, querystring, warnings)

    if (method == null) {
      method = body == null ? 'GET' : 'POST'
    }

    var ignore = options.ignore
    if (typeof ignore === 'number') {
      options.ignore = [ignore]
    }

    var path = ''

    if ((index) != null && (type) != null) {
      path = '/' + encodeURIComponent(index) + '/' + encodeURIComponent(type) + '/' + '_search'
    } else if ((index) != null) {
      path = '/' + encodeURIComponent(index) + '/' + '_search'
    } else {
      path = '/' + '_search'
    }

    // build request object
    const request = {
      method,
      path,
      body: body || '',
      querystring
    }

    options.warnings = warnings.length === 0 ? null : warnings
    return makeRequest(request, options, callback)
  }
}
783187
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'document' in _dict:
            args['document'] = DocumentSentimentResults._from_dict(
                _dict.get('document'))
        if 'targets' in _dict:
            args['targets'] = [
                TargetedSentimentResults._from_dict(x)
                for x in (_dict.get('targets'))
            ]
        return cls(**args)
1296409
def mapped(cls, key='id', **kwargs):
    """"""
    kwargs.setdefault('metadata', {})
    kwargs['metadata']['jsonldPredicate'] = {'mapSubject': key}
    kwargs.setdefault('default', attr.Factory(list))

    def converter(value):
        """Convert mapping to a list of instances."""
        if isinstance(value, dict):
            result = []
            for k, v in iteritems(value):
                if not hasattr(cls, 'from_cwl'):
                    vv = dict(v)
                    vv[key] = k
                else:
                    vv = attr.evolve(cls.from_cwl(v), **{key: k})
                result.append(vv)
        else:
            result = value

        def fix_keys(data):
            """Fix names of keys."""
            for a in fields(cls):
                a_name = a.name.rstrip('_')
                if a_name in data:
                    yield a.name, data[a_name]

        return [
            cls(**{kk: vv
                   for kk, vv in fix_keys(v)}) if not isinstance(v, cls) else v
            for v in result
        ]

    kwargs['converter'] = converter
    return attr.ib(**kwargs)
950639
def result_object(index)
      klass = "Udongo::Search::ResultObjects::#{namespace}::#{index.searchable_type}"
      klass = 'Udongo::Search::ResultObjects::Base' unless result_object_exists?(klass)
      klass.constantize.new(index, search_context: self)
    end
1143056
function buildGet (opts) {
  // eslint-disable-next-line no-unused-vars
  const { makeRequest, ConfigurationError, handleError, snakeCaseKeys } = opts
  /**
   * Perform a [get](http://www.elastic.co/guide/en/elasticsearch/reference/master/docs-get.html) request
   *
   * @param {string} id - The document ID
   * @param {string} index - The name of the index
   * @param {string} type - The type of the document (use `_all` to fetch the first document matching the ID across all types)
   * @param {list} stored_fields - A comma-separated list of stored fields to return in the response
   * @param {string} parent - The ID of the parent document
   * @param {string} preference - Specify the node or shard the operation should be performed on (default: random)
   * @param {boolean} realtime - Specify whether to perform the operation in realtime or search mode
   * @param {boolean} refresh - Refresh the shard containing the document before performing the operation
   * @param {string} routing - Specific routing value
   * @param {list} _source - True or false to return the _source field or not, or a list of fields to return
   * @param {list} _source_excludes - A list of fields to exclude from the returned _source field
   * @param {list} _source_includes - A list of fields to extract and return from the _source field
   * @param {number} version - Explicit version number for concurrency control
   * @param {enum} version_type - Specific version type
   */

  const acceptedQuerystring = [
    'stored_fields',
    'parent',
    'preference',
    'realtime',
    'refresh',
    'routing',
    '_source',
    '_source_excludes',
    '_source_includes',
    'version',
    'version_type',
    'pretty',
    'human',
    'error_trace',
    'source',
    'filter_path'
  ]

  const snakeCase = {
    storedFields: 'stored_fields',
    _sourceExcludes: '_source_excludes',
    _sourceIncludes: '_source_includes',
    versionType: 'version_type',
    errorTrace: 'error_trace',
    filterPath: 'filter_path'
  }

  return function get (params, options, callback) {
    options = options || {}
    if (typeof options === 'function') {
      callback = options
      options = {}
    }
    if (typeof params === 'function' || params == null) {
      callback = params
      params = {}
      options = {}
    }

    // check required parameters
    if (params['id'] == null) {
      const err = new ConfigurationError('Missing required parameter: id')
      return handleError(err, callback)
    }
    if (params['index'] == null) {
      const err = new ConfigurationError('Missing required parameter: index')
      return handleError(err, callback)
    }
    if (params.body != null) {
      const err = new ConfigurationError('This API does not require a body')
      return handleError(err, callback)
    }

    // validate headers object
    if (options.headers != null && typeof options.headers !== 'object') {
      const err = new ConfigurationError(`Headers should be an object, instead got: ${typeof options.headers}`)
      return handleError(err, callback)
    }

    var warnings = []
    var { method, body, id, index, type, ...querystring } = params
    querystring = snakeCaseKeys(acceptedQuerystring, snakeCase, querystring, warnings)

    if (method == null) {
      method = 'GET'
    }

    var ignore = options.ignore
    if (typeof ignore === 'number') {
      options.ignore = [ignore]
    }

    var path = ''

    if ((index) != null && (type) != null && (id) != null) {
      path = '/' + encodeURIComponent(index) + '/' + encodeURIComponent(type) + '/' + encodeURIComponent(id)
    } else {
      path = '/' + encodeURIComponent(index) + '/' + '_doc' + '/' + encodeURIComponent(id)
    }

    // build request object
    const request = {
      method,
      path,
      body: null,
      querystring
    }

    options.warnings = warnings.length === 0 ? null : warnings
    return makeRequest(request, options, callback)
  }
}
652653
def object_url(self, object_t, object_id=None, relation=None, **kwargs):
        
        if object_t not in self.objects_types:
            raise TypeError("{} is not a valid type".format(object_t))
        request_items = (
            str(item) for item in [object_t, object_id, relation] if item is not None
        )
        request = "/".join(request_items)
        base_url = self.url(request)
        if self.access_token is not None:
            kwargs["access_token"] = str(self.access_token)
        if kwargs:
            for key, value in kwargs.items():
                if not isinstance(value, str):
                    kwargs[key] = str(value)
            # kwargs are sorted (for consistent tests between Python < 3.7 and >= 3.7)
            sorted_kwargs = SortedDict.from_dict(kwargs)
            result = "{}?{}".format(base_url, urlencode(sorted_kwargs))
        else:
            result = base_url
        return result
209424
def _create_indexer(cls, name, indexer):
        """"""
        if getattr(cls, name, None) is None:
            _indexer = functools.partial(indexer, name)
            setattr(cls, name, property(_indexer, doc=indexer.__doc__))
1282189
public void createMapping(String indexName, String mappingName, ArrayList<XContentBuilder> mappingSource) {
        IndicesExistsResponse existsResponse = this.client.admin().indices().prepareExists(indexName).execute()
                .actionGet();
        //If the index does not exists, it will be created without options
        if (!existsResponse.isExists()) {
            if (!createSingleIndex(indexName)) {
                throw new ElasticsearchException("Failed to create " + indexName
                        + " index.");
            }
        }
        BulkRequestBuilder bulkRequest = this.client.prepareBulk();
        for (int i = 0; i < mappingSource.size(); i++) {
            int aux = i + 1;

            IndexRequestBuilder res = this.client
                    .prepareIndex(indexName, mappingName, String.valueOf(aux)).setSource(mappingSource.get(i));
            bulkRequest.add(res);
        }
        bulkRequest.execute();
    }
1130276
def to_representation(self, obj):
        
        kwargs = None
        for field in self.lookup_fields:
            if hasattr(obj, field):
                kwargs = {field: getattr(obj, field)}
                break
        if kwargs is None:
            raise AttributeError('Related object does not have any of lookup_fields')
        request = self._get_request()
        return request.build_absolute_uri(reverse(self._get_url(obj), kwargs=kwargs))
1180180
def default(self, value):
        """"""
        if isinstance(value, ObjectId):
            return str(value)
        return super(ElasticJSONSerializer, self).default(value)
185192
function buildMsearch (opts) {
  // eslint-disable-next-line no-unused-vars
  const { makeRequest, ConfigurationError, handleError, snakeCaseKeys } = opts
  /**
   * Perform a [msearch](http://www.elastic.co/guide/en/elasticsearch/reference/master/search-multi-search.html) request
   *
   * @param {list} index - A comma-separated list of index names to use as default
   * @param {list} type - A comma-separated list of document types to use as default
   * @param {enum} search_type - Search operation type
   * @param {number} max_concurrent_searches - Controls the maximum number of concurrent searches the multi search api will execute
   * @param {boolean} typed_keys - Specify whether aggregation and suggester names should be prefixed by their respective types in the response
   * @param {number} pre_filter_shard_size - A threshold that enforces a pre-filter roundtrip to prefilter search shards based on query rewriting if the number of shards the search request expands to exceeds the threshold. This filter roundtrip can limit the number of shards significantly if for instance a shard can not match any documents based on it's rewrite method ie. if date filters are mandatory to match but the shard bounds and the query are disjoint.
   * @param {number} max_concurrent_shard_requests - The number of concurrent shard requests each sub search executes concurrently. This value should be used to limit the impact of the search on the cluster in order to limit the number of concurrent shard requests
   * @param {boolean} rest_total_hits_as_int - Indicates whether hits.total should be rendered as an integer or an object in the rest search response
   * @param {boolean} ccs_minimize_roundtrips - Indicates whether network round-trips should be minimized as part of cross-cluster search requests execution
   * @param {object} body - The request definitions (metadata-search request definition pairs), separated by newlines
   */

  const acceptedQuerystring = [
    'search_type',
    'max_concurrent_searches',
    'typed_keys',
    'pre_filter_shard_size',
    'max_concurrent_shard_requests',
    'rest_total_hits_as_int',
    'ccs_minimize_roundtrips',
    'pretty',
    'human',
    'error_trace',
    'source',
    'filter_path'
  ]

  const snakeCase = {
    searchType: 'search_type',
    maxConcurrentSearches: 'max_concurrent_searches',
    typedKeys: 'typed_keys',
    preFilterShardSize: 'pre_filter_shard_size',
    maxConcurrentShardRequests: 'max_concurrent_shard_requests',
    restTotalHitsAsInt: 'rest_total_hits_as_int',
    ccsMinimizeRoundtrips: 'ccs_minimize_roundtrips',
    errorTrace: 'error_trace',
    filterPath: 'filter_path'
  }

  return function msearch (params, options, callback) {
    options = options || {}
    if (typeof options === 'function') {
      callback = options
      options = {}
    }
    if (typeof params === 'function' || params == null) {
      callback = params
      params = {}
      options = {}
    }

    // check required parameters
    if (params['body'] == null) {
      const err = new ConfigurationError('Missing required parameter: body')
      return handleError(err, callback)
    }

    // check required url components
    if (params['type'] != null && (params['index'] == null)) {
      const err = new ConfigurationError('Missing required parameter of the url: index')
      return handleError(err, callback)
    }

    // validate headers object
    if (options.headers != null && typeof options.headers !== 'object') {
      const err = new ConfigurationError(`Headers should be an object, instead got: ${typeof options.headers}`)
      return handleError(err, callback)
    }

    var warnings = []
    var { method, body, index, type, ...querystring } = params
    querystring = snakeCaseKeys(acceptedQuerystring, snakeCase, querystring, warnings)

    if (method == null) {
      method = body == null ? 'GET' : 'POST'
    }

    var ignore = options.ignore
    if (typeof ignore === 'number') {
      options.ignore = [ignore]
    }

    var path = ''

    if ((index) != null && (type) != null) {
      path = '/' + encodeURIComponent(index) + '/' + encodeURIComponent(type) + '/' + '_msearch'
    } else if ((index) != null) {
      path = '/' + encodeURIComponent(index) + '/' + '_msearch'
    } else {
      path = '/' + '_msearch'
    }

    // build request object
    const request = {
      method,
      path,
      bulkBody: body,
      querystring
    }

    options.warnings = warnings.length === 0 ? null : warnings
    return makeRequest(request, options, callback)
  }
}