搭建好服务器之后,启动服务器

搭建好服务器之后,启动服务器,出现:
DEBUG response status: 404 :/home/tclxa/.virtualenvs/zamboni/lib/python2.6/site-packages/pyelasticsearch/client.py:252

cilent.py文件如下:
# -*- coding: utf-8 -*-
from future import absolute_import

from datetime import datetime
from operator import itemgetter
from functools import wraps
from logging import getLogger
import re
from six import (iterkeys, binary_type, text_type, string_types, integer_types,
iteritems, PY3)
from six.moves import xrange

try:
# PY3
from urllib.parse import urlencode, quote_plus
except ImportError:
# PY2
from urllib import urlencode, quote_plus

import requests
import simplejson as json # for use_decimal
from simplejson import JSONDecodeError

from pyelasticsearch.downtime import DowntimePronePool
from pyelasticsearch.exceptions import (Timeout, ConnectionError,
ElasticHttpError,
InvalidJsonResponseError,
ElasticHttpNotFoundError,
IndexAlreadyExistsError)

def _add_es_kwarg_docs(params, method):
"""
Add stub documentation for any args in params that aren't already in
the docstring of method.

The stubs may not tell much about each arg, but they serve the important
purpose of letting the user know that they're safe to use--we won't be
paving over them in the future for something pyelasticsearch-specific.
"""
def docs_for_kwarg(p):
    return '\n        :arg %s: See the ES docs.' % p

doc = method.__doc__
if doc is not None:  # It's none under python -OO.
    # Handle the case where there are no :arg declarations to key off:
    if '\n        :arg' not in doc and params:
        first_param, params = params[0], params[1:]
        doc = doc.replace('\n        (Insert es_kwargs here.)',
                          docs_for_kwarg(first_param))

    for p in params:
        if ('\n        :arg %s: ' % p) not in doc:
            # Find the last documented arg so we can put our generated docs
            # after it. No need to explicitly compile this; the regex cache
            # should serve.
            insertion_point = re.search(
                r'        :arg (.*?)(?=\n+        (?:$|[^: ]))',
                doc,
                re.MULTILINE | re.DOTALL).end()

            doc = ''.join([doc[:insertion_point],
                           docs_for_kwarg(p),
                           doc[insertion_point:]])
    method.__doc__ = doc

def es_kwargs(*args_to_convert):
"""
Mark which kwargs will become query string params in the eventual ES call.

Return a decorator that grabs the kwargs of the given names, plus any
beginning with "es_", subtracts them from the ordinary kwargs, and passes
them to the decorated function through the ``query_params`` kwarg. The
remaining kwargs and the args are passed through unscathed.

Also, if any of the given kwargs are undocumented in the decorated method's
docstring, add stub documentation for them.
"""
convertible_args = set(args_to_convert)

def decorator(func):
    # Add docs for any missing query params:
    _add_es_kwarg_docs(args_to_convert, func)

    @wraps(func)
    def decorate(*args, **kwargs):
        # Make kwargs the map of normal kwargs and query_params the map of
        # kwargs destined for query string params:
        query_params = {}
        for k in list(iterkeys(kwargs)):  # Make a copy; we mutate kwargs.
            if k.startswith('es_'):
                query_params[k[3:]] = kwargs.pop(k)
            elif k in convertible_args:
                query_params[k] = kwargs.pop(k)
        return func(*args, query_params=query_params, **kwargs)
    return decorate
return decorator

class ElasticSearch(object):
"""
An object which manages connections to elasticsearch and acts as a
go-between for API calls to it

This object is thread-safe. You can create one instance and share it
among all threads.
"""
def __init__(self, urls, timeout=60, max_retries=0, revival_delay=300):
    """
    :arg urls: A URL or iterable of URLs of ES nodes. These are full URLs
        with port numbers, like ``http://elasticsearch.example.com:9200``.
    :arg timeout: Number of seconds to wait for each request before raising
        Timeout
    :arg max_retries: How many other servers to try, in series, after a
        request times out or a connection fails
    :arg revival_delay: Number of seconds for which to avoid a server after
        it times out or is uncontactable
    """
    if isinstance(urls, string_types):
        urls = [urls]
    urls = [u.rstrip('/') for u in urls]
    self.servers = DowntimePronePool(urls, revival_delay)
    self.revival_delay = revival_delay
    self.timeout = timeout
    self.max_retries = max_retries
    self.logger = getLogger('pyelasticsearch')
    self.session = requests.session()
    self.json_encoder = JsonEncoder

def _concat(self, items):
    """
    Return a comma-delimited concatenation of the elements of ``items``,
    with any occurrences of "_all" omitted.

    If ``items`` is a string, promote it to a 1-item list.
    """
    # TODO: Why strip out _all?
    if items is None:
        return ''
    if isinstance(items, string_types):
        items = [items]
    return ','.join(i for i in items if i != '_all')

def _to_query(self, obj):
    """
    Convert a native-Python object to a unicode or bytestring
    representation suitable for a query string.
    """
    # Quick and dirty thus far
    if isinstance(obj, string_types):
        return obj
    if isinstance(obj, bool):
        return 'true' if obj else 'false'
    if isinstance(obj, integer_types):
        return str(obj)
    if isinstance(obj, float):
        return repr(obj)  # str loses precision.
    if isinstance(obj, (list, tuple)):
        return ','.join(self._to_query(o) for o in obj)
    iso = _iso_datetime(obj)
    if iso:
        return iso
    raise TypeError("_to_query() doesn't know how to represent %r in an ES"
                    ' query string.' % obj)

def _utf8(self, thing):
    """Convert any arbitrary ``thing`` to a utf-8 bytestring."""
    if isinstance(thing, binary_type):
        return thing
    if not isinstance(thing, text_type):
        thing = text_type(thing)
    return thing.encode('utf-8')

def _join_path(self, path_components):
    """
    Smush together the path components, omitting '' and None ones.

    Unicodes get encoded to strings via utf-8. Incoming strings are assumed
    to be utf-8-encoded already.
    """
    path = '/'.join(quote_plus(self._utf8(p), '') for p in path_components if
                    p is not None and p != '')

    if not path.startswith('/'):
        path = '/' + path
    return path

def send_request(self,
                 method,
                 path_components,
                 body='',
                 query_params=None,
                 encode_body=True):
    """
    Send an HTTP request to ES, and return the JSON-decoded response.

    This is mostly an internal method, but it also comes in handy if you
    need to use a brand new ES API that isn't yet explicitly supported by
    pyelasticsearch, while still taking advantage of our connection pooling
    and retrying.

    Retry the request on different servers if the first one is down and
    ``self.max_retries`` > 0.

    :arg method: An HTTP method, like "GET"
    :arg path_components: An iterable of path components, to be joined by
        "/"
    :arg body: The request body
    :arg query_params: A map of querystring param names to values or
        ``None``
    :arg encode_body: Whether to encode the body of the request as JSON
    """
    path = self._join_path(path_components)
    if query_params:
        path = '?'.join(
            [path,
             urlencode(dict((k, self._utf8(self._to_query(v))) for k, v in
                            iteritems(query_params)))])

    request_body = self._encode_json(body) if encode_body else body
    req_method = getattr(self.session, method.lower())

    # We do our own retrying rather than using urllib3's; we want to retry
    # a different node in the cluster if possible, not the same one again
    # (which may be down).
    for attempt in xrange(self.max_retries + 1):
        server_url, was_dead = self.servers.get()
        url = server_url + path        
    self.logger.debug(
            "Making a request equivalent to this: curl -X%s '%s' -d '%s'",
            method, url, request_body)

        try:
            resp = req_method(
                url,
                timeout=self.timeout,
                **({'data': request_body} if body else {}))
        except (ConnectionError, Timeout):
            self.servers.mark_dead(server_url)
            self.logger.info('%s marked as dead for %s seconds.',
                             server_url,
                             self.revival_delay)
            if attempt >= self.max_retries:
                raise
        else:
            if was_dead:
                self.servers.mark_live(server_url)
            break


self.logger.debug('response status: %s', resp.status_code)
print'****************************************************'
print resp.status_code
    print'****************************************************'
    prepped_response = self._decode_response(resp)
    if resp.status_code >= 400:
        self._raise_exception(resp, prepped_response)
    self.logger.debug('got response %s', prepped_response)
    return prepped_response

def _raise_exception(self, response, decoded_body):
    """Raise an exception based on an error-indicating response from ES."""
    error_message = decoded_body.get('error', decoded_body)

    error_class = ElasticHttpError
    if response.status_code == 404:
        error_class = ElasticHttpNotFoundError
    elif (error_message.startswith('IndexAlreadyExistsException') or
          'nested: IndexAlreadyExistsException' in error_message):
        error_class = IndexAlreadyExistsError

    raise error_class(response.status_code, error_message)

def _encode_json(self, value):
    """
    Convert a Python value to a form suitable for ElasticSearch's JSON DSL.
    """
    return json.dumps(value, cls=self.json_encoder, use_decimal=True)

def _decode_response(self, response):
    """Return a native-Python representation of a response's JSON blob."""
    try:
        json_response = response.json()
    except JSONDecodeError:
        raise InvalidJsonResponseError(response)
    return json_response

## REST API

@es_kwargs('routing', 'parent', 'timestamp', 'ttl', 'percolate',
           'consistency', 'replication', 'refresh', 'timeout', 'fields')
def index(self, index, doc_type, doc, id=None, overwrite_existing=True,
          query_params=None):
    """
    Put a typed JSON document into a specific index to make it searchable.

    :arg index: The name of the index to which to add the document
    :arg doc_type: The type of the document
    :arg doc: A Python mapping object, convertible to JSON, representing
        the document
    :arg id: The ID to give the document. Leave blank to make one up.
    :arg overwrite_existing: Whether we should overwrite existing documents
        of the same ID and doctype
    :arg routing: A value hashed to determine which shard this indexing
        request is routed to
    :arg parent: The ID of a parent document, which leads this document to
        be routed to the same shard as the parent, unless ``routing``
        overrides it.
    :arg timestamp: An explicit value for the (typically automatic)
        timestamp associated with a document, for use with ``ttl`` and such
    :arg ttl: The time until this document is automatically removed from
        the index. Can be an integral number of milliseconds or a duration
        like '1d'.
    :arg percolate: An indication of which percolator queries, registered
        against this index, should be checked against the new document: '*'
        or a query string like 'color:green'
    :arg consistency: An indication of how many active shards the contact
        node should demand to see in order to let the index operation
        succeed: 'one', 'quorum', or 'all'
    :arg replication: Set to 'async' to return from ES before finishing
        replication.
    :arg refresh: Pass True to refresh the index after adding the document.
    :arg timeout: A duration to wait for the relevant primary shard to
        become available, in the event that it isn't: for example, "5m"

    See `ES's index API`_ for more detail.

    .. _`ES's index API`:
        http://www.elasticsearch.org/guide/reference/api/index_.html
    """
    # :arg query_params: A map of other querystring params to pass along to
    # ES. This lets you use future ES features without waiting for an
    # update to pyelasticsearch. If we just used **kwargs for this, ES
    # could start using a querystring param that we already used as a
    # kwarg, and we'd shadow it. Name these params according to the names
    # they have in ES's REST API, but prepend "\es_": for example,
    # ``es_version=2``.

    # TODO: Support version along with associated "preference" and
    # "version_type" params.
    if not overwrite_existing:
        query_params['op_type'] = 'create'

    return self.send_request('POST' if id is None else 'PUT',
                             [index, doc_type, id],
                             doc,
                             query_params)

@es_kwargs('consistency', 'refresh')
def bulk_index(self, index, doc_type, docs, id_field='id',
               parent_field='_parent', query_params=None):
    """
    Index a list of documents as efficiently as possible.

    :arg index: The name of the index to which to add the document
    :arg doc_type: The type of the document
    :arg docs: An iterable of Python mapping objects, convertible to JSON,
        representing documents to index
    :arg id_field: The field of each document that holds its ID
    :arg parent_field: The field of each document that holds its parent ID,
        if any. Removed from document before indexing. 

    See `ES's bulk API`_ for more detail.

    .. _`ES's bulk API`:
        http://www.elasticsearch.org/guide/reference/api/bulk.html
    """
    body_bits = []

    if not docs:
        raise ValueError('No documents provided for bulk indexing!')

    for doc in docs:
        action = {'index': {'_index': index, '_type': doc_type}}

        if doc.get(id_field) is not None:
            action['index']['_id'] = doc[id_field]

        if doc.get(parent_field) is not None:
            action['index']['_parent'] = doc.pop(parent_field)

        body_bits.append(self._encode_json(action))
        body_bits.append(self._encode_json(doc))

    # Need the trailing newline.
    body = '\n'.join(body_bits) + '\n'
    return self.send_request('POST',
                             ['_bulk'],
                             body,
                             encode_body=False,
                             query_params=query_params)

@es_kwargs('routing', 'parent', 'replication', 'consistency', 'refresh')
def delete(self, index, doc_type, id, query_params=None):
    """
    Delete a typed JSON document from a specific index based on its ID.

    :arg index: The name of the index from which to delete
    :arg doc_type: The type of the document to delete
    :arg id: The (string or int) ID of the document to delete

    See `ES's delete API`_ for more detail.

    .. _`ES's delete API`:
        http://www.elasticsearch.org/guide/reference/api/delete.html
    """
    # id should never be None, and it's not particular dangerous
    # (equivalent to deleting a doc with ID "None", but it's almost
    # certainly not what the caller meant:
    if id is None or id == '':
        raise ValueError('No ID specified. To delete all documents in '
                         'an index, use delete_all().')
    return self.send_request('DELETE', [index, doc_type, id],
                             query_params=query_params)

@es_kwargs('routing', 'parent', 'replication', 'consistency', 'refresh')
def delete_all(self, index, doc_type, query_params=None):
    """
    Delete all documents of the given doctype from an index.

    :arg index: The name of the index from which to delete. ES does not
        support this being empty or "_all" or a comma-delimited list of
        index names (in 0.19.9).
    :arg doc_type: The name of a document type

    See `ES's delete API`_ for more detail.

    .. _`ES's delete API`:
        http://www.elasticsearch.org/guide/reference/api/delete.html
    """
    return self.send_request('DELETE', [index, doc_type],
                             query_params=query_params)

@es_kwargs('q', 'df', 'analyzer', 'default_operator', 'source' 'routing',
           'replication', 'consistency')
def delete_by_query(self, index, doc_type, query, query_params=None):
    """
    Delete typed JSON documents from a specific index based on query.

    :arg index: An index or iterable thereof from which to delete
    :arg doc_type: The type of document or iterable thereof to delete
    :arg query: A dictionary that will convert to ES's query DSL or a
        string that will serve as a textual query to be passed as the ``q``
        query string parameter. (Passing the ``q`` kwarg yourself is
        deprecated.)

    See `ES's delete-by-query API`_ for more detail.

    .. _`ES's delete-by-query API`:
        http://www.elasticsearch.org/guide/reference/api/delete-by-query.html
    """
    if isinstance(query, string_types) and 'q' not in query_params:
        query_params['q'] = query
        body = ''
    else:
        body = query
    return self.send_request(
        'DELETE',
        [self._concat(index), self._concat(doc_type), '_query'],
        body,
        query_params=query_params)

@es_kwargs('realtime', 'fields', 'routing', 'preference', 'refresh')
def get(self, index, doc_type, id, query_params=None):
    """
    Get a typed JSON document from an index by ID.

    :arg index: The name of the index from which to retrieve
    :arg doc_type: The type of document to get
    :arg id: The ID of the document to retrieve

    See `ES's get API`_ for more detail.

    .. _`ES's get API`:
        http://www.elasticsearch.org/guide/reference/api/get.html
    """
    return self.send_request('GET', [index, doc_type, id],
                             query_params=query_params)

@es_kwargs()
def multi_get(self, ids, index=None, doc_type=None, fields=None,
              query_params=None):
    """
    Get multiple typed JSON documents from ES.

    :arg ids: An iterable, each element of which can be either an a dict or
        an id (int or string). IDs are taken to be document IDs. Dicts are
        passed through the Multi Get API essentially verbatim, except that
        any missing ``_type``, ``_index``, or ``fields`` keys are filled in
        from the defaults given in the ``index``, ``doc_type``, and
        ``fields`` args.
    :arg index: Default index name from which to retrieve
    :arg doc_type: Default type of document to get
    :arg fields: Default fields to return

    See `ES's Multi Get API`_ for more detail.

    .. _`ES's Multi Get API`:
        http://www.elasticsearch.org/guide/reference/api/multi-get.html
    """
    doc_template = dict(
        filter(
            itemgetter(1),
            [('_index', index), ('_type', doc_type), ('fields', fields)]))

    docs = []
    for id in ids:
        doc = doc_template.copy()
        if isinstance(id, dict):
            doc.update(id)
        else:
            doc['_id'] = id
        docs.append(doc)

    return self.send_request(
        'GET', ['_mget'], {'docs': docs}, query_params=query_params)

@es_kwargs('routing', 'parent', 'timeout', 'replication', 'consistency',
           'percolate', 'refresh', 'retry_on_conflict', 'fields')
def update(self, index, doc_type, id, script=None, params=None, lang=None,
           query_params=None, doc=None, upsert=None):
    """
    Update an existing document. Raise ``TypeError`` if ``script``, ``doc``
    and ``upsert`` are all unspecified.

    :arg index: The name of the index containing the document
    :arg doc_type: The type of the document
    :arg id: The ID of the document
    :arg script: The script to be used to update the document
    :arg params: A dict of the params to be put in scope of the script
    :arg lang: The language of the script. Omit to use the default,
        specified by ``script.default_lang``.
    :arg doc: A partial document to be merged into the existing document
    :arg upsert: The content for the new document created if the document
        does not exist
    """
    if script is None and doc is None and upsert is None:
        raise TypeError('At least one of the script, doc, or upsert '
                        'kwargs must be provided.')

    body = {}
    if script:
        body['script'] = script
    if lang and script:
        body['lang'] = lang
    if doc:
        body['doc'] = doc
    if upsert:
        body['upsert'] = upsert
    if params:
        body['params'] = params
    return self.send_request(
        'POST',
        [index, doc_type, id, '_update'],
        body=body,
        query_params=query_params)

def _search_or_count(self, kind, query, index=None, doc_type=None,
                     query_params=None):
    if isinstance(query, string_types):
        query_params['q'] = query
        body = ''
    else:
        body = query

    return self.send_request(
        'GET',
        [self._concat(index), self._concat(doc_type), kind],
        body,
        query_params=query_params)

@es_kwargs('routing', 'size')
def search(self, query, **kwargs):
    """
    Execute a search query against one or more indices and get back search
    hits.

    :arg query: A dictionary that will convert to ES's query DSL or a
        string that will serve as a textual query to be passed as the ``q``
        query string parameter
    :arg index: An index or iterable of indexes to search. Omit to search
        all.
    :arg doc_type: A document type or iterable thereof to search. Omit to
        search all.
    :arg size: Limit the number of results to ``size``. Use with ``es_from`` to
        implement paginated searching.

    See `ES's search API`_ for more detail.

    .. _`ES's search API`:
        http://www.elasticsearch.org/guide/reference/api/search/
    """
    return self._search_or_count('_search', query, **kwargs)

@es_kwargs('df', 'analyzer', 'default_operator', 'source', 'routing')
def count(self, query, **kwargs):
    """
    Execute a query against one or more indices and get hit count.

    :arg query: A dictionary that will convert to ES's query DSL or a
        string that will serve as a textual query to be passed as the ``q``
        query string parameter
    :arg index: An index or iterable of indexes to search. Omit to search
        all.
    :arg doc_type: A document type or iterable thereof to search. Omit to
        search all.

    See `ES's count API`_ for more detail.

    .. _`ES's count API`:
        http://www.elasticsearch.org/guide/reference/api/count.html
    """
    return self._search_or_count('_count', query, **kwargs)

@es_kwargs()
def get_mapping(self, index=None, doc_type=None, query_params=None):
    """
    Fetch the mapping definition for a specific index and type.

    :arg index: An index or iterable thereof
    :arg doc_type: A document type or iterable thereof

    Omit both arguments to get mappings for all types and indexes.

    See `ES's get-mapping API`_ for more detail.

    .. _`ES's get-mapping API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-get-mapping.html
    """
    # TODO: Think about turning index=None into _all if doc_type is non-
    # None, per the ES doc page.
    return self.send_request(
        'GET',
        [self._concat(index), self._concat(doc_type), '_mapping'],
        query_params=query_params)

@es_kwargs('ignore_conflicts')
def put_mapping(self, index, doc_type, mapping, query_params=None):
    """
    Register specific mapping definition for a specific type against one or
    more indices.

    :arg index: An index or iterable thereof
    :arg doc_type: The document type to set the mapping of
    :arg mapping: A dict representing the mapping to install. For example,
        this dict can have top-level keys that are the names of doc types.

    See `ES's put-mapping API`_ for more detail.

    .. _`ES's put-mapping API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-put-mapping.html
    """
    # TODO: Perhaps add a put_all_mappings() for consistency and so we
    # don't need to expose the "_all" magic string. We haven't done it yet
    # since this routine is not dangerous: ES makes you explicily pass
    # "_all" to update all mappings.
    return self.send_request(
        'PUT',
        [self._concat(index), doc_type, '_mapping'],
        mapping,
        query_params=query_params)

@es_kwargs('search_type', 'search_indices', 'search_types',
           'search_scroll', 'search_size', 'search_from',
           'like_text', 'percent_terms_to_match', 'min_term_freq',
           'max_query_terms', 'stop_words', 'min_doc_freq', 'max_doc_freq',
           'min_word_len', 'max_word_len', 'boost_terms', 'boost',
           'analyzer')
def more_like_this(self, index, doc_type, id, mlt_fields, body='', query_params=None):
    """
    Execute a "more like this" search query against one or more fields and
    get back search hits.

    :arg index: The index to search and where the document for comparison
        lives
    :arg doc_type: The type of document to find others like
    :arg id: The ID of the document to find others like
    :arg mlt_fields: The list of fields to compare on
    :arg body: A dictionary that will convert to ES's query DSL and be
        passed as the request body

    See `ES's more-like-this API`_ for more detail.

    .. _`ES's more-like-this API`:
        http://www.elasticsearch.org/guide/reference/api/more-like-this.html
    """
    query_params['mlt_fields'] = self._concat(mlt_fields)
    return self.send_request('GET',
                             [index, doc_type, id, '_mlt'],
                             body=body,
                             query_params=query_params)

## Index Admin API

@es_kwargs('recovery', 'snapshot')
def status(self, index=None, query_params=None):
    """
    Retrieve the status of one or more indices

    :arg index: An index or iterable thereof

    See `ES's index-status API`_ for more detail.

    .. _`ES's index-status API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-status.html
    """
    return self.send_request('GET', [self._concat(index), '_status'],
                             query_params=query_params)

@es_kwargs()
def update_aliases(self, settings, query_params=None):
    """
    Add, remove, or update aliases in bulk.

    :arg settings: a dictionary specifying the actions to perform

    See `ES's admin-indices-aliases API`_.

    .. _`ES's admin-indices-aliases API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-aliases.html
    """
    return self.send_request('POST', ['_aliases'],
                             body=settings, query_params=query_params)

@es_kwargs()
def aliases(self, index=None, query_params=None):
    """
    Retrieve a listing of aliases

    :arg index: the name of an index or an iterable of indices

    See `ES's admin-indices-aliases API`_.

    .. _`ES's admin-indices-aliases API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-aliases.html
    """
    return self.send_request('GET', [self._concat(index), '_aliases'],
                             query_params=query_params)

@es_kwargs()
def create_index(self, index, settings=None, query_params=None):
    """
    Create an index with optional settings.

    :arg index: The name of the index to create
    :arg settings: A dictionary of settings

    If the index already exists, raise
    :class:`~pyelasticsearch.exceptions.IndexAlreadyExistsError`.

    See `ES's create-index API`_ for more detail.

    .. _`ES's create-index API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-create-index.html
    """
    return self.send_request('PUT', [index], body=settings,
                             query_params=query_params)

@es_kwargs()
def delete_index(self, index, query_params=None):
    """
    Delete an index.

    :arg index: An index or iterable thereof to delete

    If the index is not found, raise
    :class:`~pyelasticsearch.exceptions.ElasticHttpNotFoundError`.

    See `ES's delete-index API`_ for more detail.

    .. _`ES's delete-index API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-delete-index.html
    """
    if not index:
        raise ValueError('No indexes specified. To delete all indexes, use'
                         ' delete_all_indexes().')
    return self.send_request('DELETE', [self._concat(index)],
                             query_params=query_params)

def delete_all_indexes(self, **kwargs):
    """Delete all indexes."""
    return self.delete_index('_all', **kwargs)

@es_kwargs()
def close_index(self, index, query_params=None):
    """
    Close an index.

    :arg index: The index to close

    See `ES's close-index API`_ for more detail.

    .. _`ES's close-index API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-open-close.html
    """
    return self.send_request('POST', [index, '_close'],
                             query_params=query_params)

@es_kwargs()
def open_index(self, index, query_params=None):
    """
    Open an index.

    :arg index: The index to open

    See `ES's open-index API`_ for more detail.

    .. _`ES's open-index API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-open-close.html
    """
    return self.send_request('POST', [index, '_open'],
                             query_params=query_params)

@es_kwargs()
def get_settings(self, index, query_params=None):
    """
    Get the settings of one or more indexes.

    :arg index: An index or iterable of indexes

    See `ES's get-settings API`_ for more detail.

    .. _`ES's get-settings API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-get-settings.html
    """
    return self.send_request('GET',
                             [self._concat(index), '_settings'],
                             query_params=query_params)

@es_kwargs()
def update_settings(self, index, settings, query_params=None):
    """
    Change the settings of one or more indexes.

    :arg index: An index or iterable of indexes
    :arg settings: A dictionary of settings

    See `ES's update-settings API`_ for more detail.

    .. _`ES's update-settings API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-update-settings.html
    """
    if not index:
        raise ValueError('No indexes specified. To update all indexes, use'
                         ' update_all_settings().')
    # If we implement the "update cluster settings" API, call that
    # update_cluster_settings().
    return self.send_request('PUT',
                            [self._concat(index), '_settings'],
                            body=settings,
                            query_params=query_params)

@es_kwargs()
def update_all_settings(self, settings, query_params=None):
    """
    Update the settings of all indexes.

    :arg settings: A dictionary of settings

    See `ES's update-settings API`_ for more detail.

    .. _`ES's update-settings API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-update-settings.html
    """
    return self.send_request('PUT', ['_settings'], body=settings,
                             query_params=query_params)

@es_kwargs('refresh')
def flush(self, index=None, query_params=None):
    """
    Flush one or more indices (clear memory).

    :arg index: An index or iterable of indexes

    See `ES's flush API`_ for more detail.

    .. _`ES's flush API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-flush.html
    """
    return self.send_request('POST',
                             [self._concat(index), '_flush'],
                             query_params=query_params)

@es_kwargs()
def refresh(self, index=None, query_params=None):
    """
    Refresh one or more indices.

    :arg index: An index or iterable of indexes

    See `ES's refresh API`_ for more detail.

    .. _`ES's refresh API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-refresh.html
    """
    return self.send_request('POST', [self._concat(index), '_refresh'],
                             query_params=query_params)

@es_kwargs()
def gateway_snapshot(self, index=None, query_params=None):
    """
    Gateway snapshot one or more indices.

    :arg index: An index or iterable of indexes

    See `ES's gateway-snapshot API`_ for more detail.

    .. _`ES's gateway-snapshot API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-gateway-snapshot.html
    """
    return self.send_request(
        'POST',
        [self._concat(index), '_gateway', 'snapshot'],
        query_params=query_params)

@es_kwargs('max_num_segments', 'only_expunge_deletes', 'refresh', 'flush',
           'wait_for_merge')
def optimize(self, index=None, query_params=None):
    """
    Optimize one or more indices.

    :arg index: An index or iterable of indexes

    See `ES's optimize API`_ for more detail.

    .. _`ES's optimize API`:
        http://www.elasticsearch.org/guide/reference/api/admin-indices-optimize.html
    """
    return self.send_request('POST',
                             [self._concat(index), '_optimize'],
                             query_params=query_params)

@es_kwargs('level', 'wait_for_status', 'wait_for_relocating_shards',
           'wait_for_nodes', 'timeout')
def health(self, index=None, query_params=None):
    """
    Report on the health of the cluster or certain indices.

    :arg index: The index or iterable of indexes to examine

    See `ES's cluster-health API`_ for more detail.

    .. _`ES's cluster-health API`:
        http://www.elasticsearch.org/guide/reference/api/admin-cluster-health.html
    """
    return self.send_request(
        'GET',
        ['_cluster', 'health', self._concat(index)],
        query_params=query_params)

@es_kwargs('filter_nodes', 'filter_routing_table', 'filter_metadata',
           'filter_blocks', 'filter_indices')
def cluster_state(self, query_params=None):
    """
    The cluster state API allows to get comprehensive state
    information of the whole cluster.

    (Insert es_kwargs here.)

    See `ES's cluster-state API`_ for more detail.

    .. _`ES's cluster-state API`:
        http://www.elasticsearch.org/guide/reference/api/admin-cluster-state.html
    """
    return self.send_request(
        'GET', ['_cluster', 'state'], query_params=query_params)

@es_kwargs()
def percolate(self, index, doc_type, doc, query_params=None):
    """
    Run a JSON document through the registered percolator queries, and
    return which ones match.

    :arg index: The name of the index to which the document pretends to
        belong
    :arg doc_type: The type the document should be treated as if it has
    :arg doc: A Python mapping object, convertible to JSON, representing
        the document

    Use :meth:`index()` to register percolators. See `ES's percolate API`_
    for more detail.

    .. _`ES's percolate API`:
        http://www.elasticsearch.org/guide/reference/api/percolate/
    """
    return self.send_request('GET',
                             [index, doc_type, '_percolate'], 
                             doc, query_params=query_params)

class JsonEncoder(json.JSONEncoder):
def default(self, value):
"""Convert more Python data types to ES-understandable JSON."""
iso = _iso_datetime(value)
if iso:
return iso
if not PY3 and isinstance(value, str):
return unicode(value, errors='replace') # TODO: Be stricter.
if isinstance(value, set):
return list(value)
return super(JsonEncoder, self).default(value)

def _iso_datetime(value):
"""
If value appears to be something datetime-like, return it in ISO format.

Otherwise, return None.
"""
if hasattr(value, 'strftime'):
    if hasattr(value, 'hour'):
        return value.isoformat()
    else:
        return '%sT00:00:00' % value.isoformat()
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
gitblit 服务器无法启动
-
markplace(应用商店) 服务器的搭建
-
项目组搭建了一个CSVN服务器,每天开机的时候,每次都需要登录的客户端启动,怎么让他默认自动启动
-
MAC搭建SVN服务器,如何连接?
-
求大佬们帮忙!在本地虚拟机搭建ftp服务器,尝试在本地物理机进行访问测试,却一直连接超时。
-
linux服务器重装之后,怎么恢复之前保存的数据啊?
-
nexus在linux端的搭建好了,在本地却无法连接
-
写一个定时器Timer,随服务器一起启动
-
gitblit服务器 后台服务启动不起来,提示:不能在本地计算机启动gitblit
-
自己搭建的ngrok服务器如何添加身份验证
-
windows7下git+copssh搭建服务器,git clone不了的问题
-
搭建CDH集群,服务器日志一直报JDBC错误。麻烦各位大神帮忙看一下
-
求教OpenStack部署服务器问题
-
ClouderaManager方式搭建CDH环境后,无法启动各个服务
-
棋牌搭建遇到网络端口错误怎么解决?
-
求linux大神,url传递中的参数带有"|",无法传到服务器,服务器是搭建在centOS上的.
-
关于windows8 server下安装nexus-3.2.0-01搭建maven私有服务器
-
lamp环境搭建过程当中mysql无法安装
-
关于Storm/Zookeeper集群配置
-
学会了这些技术,你离BAT大厂不远了
每一个程序员都有一个梦想,梦想着能够进入阿里、腾讯、字节跳动、百度等一线互联网公司,由于身边的环境等原因,不知道 BAT 等一线互联网公司使用哪些技术?或者该如何去学习这些技术?或者我该去哪些获取这些技术资料?没关系,平头哥一站式服务,上面统统不是问题。平头哥整理了 BAT 等一线大厂的必备技能,并且帮你准备了对应的资料。对于整理出来的技术,如果你掌握的不牢固,那就赶快巩固,如果你还没有涉及,现在...
程序员真是太太太太太有趣了!!!
网络上虽然已经有了很多关于程序员的话题,但大部分人对这个群体还是很陌生。我们在谈论程序员的时候,究竟该聊些什么呢?各位程序员大佬们,请让我听到你们的声音!不管你是前端开发...
史上最详细的IDEA优雅整合Maven+SSM框架(详细思路+附带源码)
网上很多整合SSM博客文章并不能让初探ssm的同学思路完全的清晰,可以试着关掉整合教程,摇两下头骨,哈一大口气,就在万事具备的时候,开整,这个时候你可能思路全无 ~中招了咩~ ,还有一些同学依旧在使用eclipse或者Myeclipse开发,我想对这些朋友说IDEA 的编译速度很快,人生苦短,来不及解释了,直接上手idea吧。这篇文章每一步搭建过程都测试过了,应该不会有什么差错。本文章还有个比较优秀的特点,就是idea的使用,基本上关于idea的操作都算是比较详细的,所以不用太担心不会撸idea!最后,本文
我花了一夜用数据结构给女朋友写个H5走迷宫游戏
起因 又到深夜了,我按照以往在csdn和公众号写着数据结构!这占用了我大量的时间!我的超越妹妹严重缺乏陪伴而 怨气满满! 而女朋友时常埋怨,认为数据结构这么抽象难懂的东西没啥作用,常会问道:天天写这玩意,有啥作用。而我答道:能干事情多了,比如写个迷宫小游戏啥的! 当我码完字准备睡觉时:写不好别睡觉! 分析 如果用数据结构与算法造出东西来呢? ...
接班马云的为何是张勇?
上海人、职业经理人、CFO 背景,集齐马云三大不喜欢的张勇怎么就成了阿里接班人? 作者|王琳 本文经授权转载自燃财经(ID:rancaijing) 9月10日,张勇转正了,他由阿里巴巴董事局候任主席正式成为阿里巴巴董事局主席,这也意味着阿里巴巴将正式开启“逍遥子时代”。 从2015年接任CEO开始,张勇已经将阿里巴巴股价拉升了超过200%。但和马云强大的个人光环比,张勇显得尤其...
让程序员崩溃的瞬间(非程序员勿入)
今天给大家带来点快乐,程序员才能看懂。 来源:https://zhuanlan.zhihu.com/p/47066521 1. 公司实习生找 Bug 2.在调试时,将断点设置在错误的位置 3.当我有一个很棒的调试想法时 4.偶然间看到自己多年前写的代码 5.当我第一次启动我的单元测试时 ...
接私活必备的 10 个开源项目!
点击蓝色“GitHubDaily”关注我加个“星标”,每天下午 18:35,带你逛 GitHub!作者 | SevDot来源 | http://1t.click/VE8W...
Spring高级技术梳理
Spring高级技术梳理 序言正文SpringDate部分Spring全家桶之SpringData——预科阶段Spring全家桶之SpringData——Spring 整合Hibernate与Hibernate JpaSpring全家桶之SpringData——Spring Data JPASpring全家桶之SpringData——SpringData RedisSpringBoot部分Sp...
如何在Windows中开启"上帝模式"
原文链接 : https://mp.weixin.qq.com/s?__biz=MzIwMjE1MjMyMw==&mid=2650202982&idx=1&sn=2c6c609ce06db1cee81abf2ba797be1b&chksm=8ee1438ab996ca9c2d0cd0f76426e92faa835beef20ae21b537c0867ec2773be...
飞天智能:阿里云的 AI 落地野心
当下,AI 业界不会否认的一个事实是,AI实力的比拼不再是单点的算法技术能力,而是从底层算法到应用平台的全面AI能力。单纯的算法,只是实验室里的乐趣,唯有结合商业的数据处...
为什么平头哥做芯片如此迅猛?
作者 | 胡巍巍 发自杭州云栖大会 责编 | 唐小引 出品 | CSDN(ID:CSDNnews) 2018年10月31日,阿里旗下的平头哥半导体有限公司成立。 如今,平头哥成立不到一年,就已成绩斐然。 2019年9月25日,阿里巴巴旗下半导体公司平头哥,发布含光800芯片。 2019年7月25日,平头哥发布成立后第一个基于RISC-V的处理器IP Core玄铁910。...
分享靠写代码赚钱的一些门路
作者 mezod,译者 josephchang10如今,通过自己的代码去赚钱变得越来越简单,不过对很多人来说依然还是很难,因为他们不知道有哪些门路。今天给大家分享一个精彩...
技术人员要拿百万年薪,必须要经历这9个段位
很多人都问,技术人员如何成长,每个阶段又是怎样的,如何才能走出当前的迷茫,实现自我的突破。所以我结合我自己10多年的从业经验,总结了技术人员成长的9个段位,希望对大家的职...
多线程编程是后台开发人员的基本功
这里先给大家分享一个小故事:在我刚开始参加工作的那年,公司安排我开发一款即时通讯软件(IM,类似于 QQ 聊天软件),在这之前我心里也知道如果多线程操作一个整型值是要加锁...
分布式、多线程、高并发都不懂,拿什么去跳槽
当提起这三个词的时候,是不是很多人都认为分布式=高并发=多线程?当面试官问到高并发系统可以采用哪些手段来解决,或者被问到分布式系统如何解决一致性的问题,是不是一脸懵逼?确...
动画:用动画给面试官解释 TCP 三次握手过程
作者 | 小鹿 来源 | 公众号:小鹿动画学编程 写在前边 TCP 三次握手过程对于面试是必考的一个,所以不但要掌握 TCP 整个握手的过程,其中有些小细节也更受到面试官的青睐。 对于这部分掌握以及 TCP 的四次挥手,小鹿将会以动画的形式呈现给每个人,这样将复杂的知识简单化,理解起来也容易了很多,尤其对于一个初学者来说。 学习导图 一、TCP 是什么? TCP(Transmissio...
为什么程序员在学习编程的时候什么都记不住?
在程序员的职业生涯中,记住所有你接触过的代码是一件不可能的事情!那么我们该如何解决这一问题?作者 |Dylan Mestyanek译者 | 弯月,责编 | 屠敏出品 |...
500行代码,教你用python写个微信飞机大战
这几天在重温微信小游戏的飞机大战,玩着玩着就在思考人生了,这飞机大战怎么就可以做的那么好,操作简单,简单上手。 帮助蹲厕族、YP族、饭圈女孩在无聊之余可以有一样东西让他们振作起来!让他们的左手 / 右手有节奏有韵律的朝着同一个方向来回移动起来! 这是史诗级的发明,是浓墨重彩的一笔,是…… 在一阵抽搐后,我结束了游戏,瞬时觉得一切都索然无味,正在我进入贤者模式时,突然想到,如果我可以让更多人已不同的方式体会到这种美轮美奂的感觉岂不美哉? 所以我打开电脑,创建了一个 `plan_game.py`……
2019诺贝尔经济学奖得主:贫穷的本质是什么?
2019年诺贝尔经济学奖,颁给了来自麻省理工学院的 阿巴希·巴纳吉(Abhijit Vinayak Banerjee)、艾丝特·杜芙若(Esther Duflo)夫妇和哈...
linux:最常见的linux命令(centOS 7.6)
最常见,最频繁使用的20个基础命令如下: 皮一下,这都是干货偶,大佬轻喷 一、linux关机命令: 1.shutdown命令安全地将系统关机(推荐)参数说明: [-r] 重启计算器。 [-h] 关机后关闭电源〔halt〕。 [-c] cancel current process取消目前正在执行的关机程序。 [-time] 设定关机〔shutdown〕前的时间。 shutdown -h now ...
只因写了一段爬虫,公司200多人被抓!
“一个程序员写了个爬虫程序,整个公司200多人被端了。” “不可能吧!” 刚从朋友听到这个消息的时候,我有点不太相信,做为一名程序员来讲,谁还没有写过几段爬虫呢?只因写爬虫程序就被端有点夸张了吧。 朋友说,消息很确认并且已经进入审判阶段了。 01.对消息进一步确认 朋友认识几个律师朋友,和他们有一些业务来往,得知他们想尝试把业务扩展到程序员这个群体。那段时间我刚好离职也有时间,在朋友...
相关热词 c#部署端口监听项目、 c#接口中的属性使用方法 c# 昨天 c#func链接匿名方法 c#怎么创建文件夹 c#从键盘接收空格 c#da/ad c#部门请假管理系统 c#服务器socket c# 默认的访问修饰符