desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Initializer.
Args:
name: The name of the field. Field names must have maximum length
MAXIMUM_FIELD_NAME_LENGTH and match pattern "[A-Za-z][A-Za-z0-9_]*".
value: The value of the field which can be a str, unicode or date.
language: The ISO 693-1 two letter code of the language used in the value.
See http://www.sil.org/... | def __init__(self, name, value, language=None):
| self._name = _CheckFieldName(_ConvertToUnicode(name))
self._value = self._CheckValue(value)
self._language = _CheckLanguage(_ConvertToUnicode(language))
|
'Returns the name of the field.'
| @property
def name(self):
| return self._name
|
'Returns the code of the language the content in value is written in.'
| @property
def language(self):
| return self._language
|
'Returns the value of the field.'
| @property
def value(self):
| return self._value
|
'Checks the value is valid for the given type.
Args:
value: The value to check.
Returns:
The checked value.'
| def _CheckValue(self, value):
| raise NotImplementedError('_CheckValue is an abstract method')
|
'Copies value to a string value in proto buf.'
| def _CopyStringValueToProtocolBuffer(self, field_value_pb):
| field_value_pb.set_string_value(self.value.encode('utf-8'))
|
'Initializer.
Args:
name: The name of the field.
value: A str or unicode object containing text.
language: The code of the language the value is encoded in.
Raises:
TypeError: If value is not a string.
ValueError: If value is longer than allowed.'
| def __init__(self, name, value=None, language=None):
| Field.__init__(self, name, _ConvertToUnicode(value), language)
|
'Initializer.
Args:
name: The name of the field.
value: A str or unicode object containing the searchable content of the
Field.
language: The code of the language the value is encoded in.
Raises:
TypeError: If value is not a string.
ValueError: If value is longer than allowed.'
| def __init__(self, name, value=None, language=None):
| Field.__init__(self, name, _ConvertToUnicode(value), language)
|
'Initializer.
Args:
name: The name of the field.
value: A str or unicode object to be treated as an indivisible text value.
language: The code of the language the value is encoded in.
Raises:
TypeError: If value is not a string.
ValueError: If value is longer than allowed.'
| def __init__(self, name, value=None, language=None):
| Field.__init__(self, name, _ConvertToUnicode(value), language)
|
'Initializer.
Args:
name: The name of the field.
value: A datetime.date but not a datetime.datetime.
Raises:
TypeError: If value is not a datetime.date or is a datetime.datetime.'
| def __init__(self, name, value=None):
| Field.__init__(self, name, value)
|
'Initializer.
Args:
name: The name of the field.
value: A numeric value.
Raises:
TypeError: If value is not numeric.
ValueError: If value is out of range.'
| def __init__(self, name, value=None):
| Field.__init__(self, name, value)
|
'Initializer.
Args:
latitude: The angle between the equatorial plan and a line that passes
through the GeoPoint, between -90 and 90 degrees.
longitude: The angle east or west from a reference meridian to another
meridian that passes through the GeoPoint, between -180 and 180 degrees.
Raises:
TypeError: If any of the pa... | def __init__(self, latitude, longitude):
| self._latitude = self._CheckLatitude(latitude)
self._longitude = self._CheckLongitude(longitude)
|
'Returns the angle between equatorial plan and line thru the geo point.'
| @property
def latitude(self):
| return self._latitude
|
'Returns the angle from a reference meridian to another meridian.'
| @property
def longitude(self):
| return self._longitude
|
'Initializer.
Args:
name: The name of the field.
value: A GeoPoint value.
Raises:
TypeError: If value is not numeric.'
| def __init__(self, name, value=None):
| Field.__init__(self, name, value)
|
'Initializer.
Args:
doc_id: The visible printable ASCII string identifying the document which
does not start with \'!\'. Whitespace is excluded from ids. If no id is
provided, the search service will provide one.
fields: An iterable of Field instances representing the content of the
document.
language: The code of the ... | def __init__(self, doc_id=None, fields=None, language='en', rank=None):
| doc_id = _ConvertToUnicode(doc_id)
if (doc_id is not None):
_CheckDocumentId(doc_id)
self._doc_id = doc_id
self._fields = _GetList(fields)
self._language = _CheckLanguage(_ConvertToUnicode(language))
self._field_map = None
doc_rank = None
if (not (rank is None)):
doc_rank... |
'Returns the document identifier.'
| @property
def doc_id(self):
| return self._doc_id
|
'Returns a list of fields of the document.'
| @property
def fields(self):
| return self._fields
|
'Returns the code of the language the document fields are written in.'
| @property
def language(self):
| return self._language
|
'Returns the rank of this document.'
| @property
def rank(self):
| return self._rank
|
'Returns the field with the provided field name.
Args:
field_name: The name of the field to return.
Returns:
A field with the given name.
Raises:
ValueError: There is not exactly one field with the given name.'
| def field(self, field_name):
| fields = self[field_name]
if (len(fields) == 1):
return fields[0]
raise ValueError(('Must have exactly one field with name %s, but found %d.' % (field_name, len(fields))))
|
'Returns a list of all fields with the provided field name.
Args:
field_name: The name of the field to return.
Returns:
All fields with the given name, or an empty list if no field with that
name exists.'
| def __getitem__(self, field_name):
| return self._BuildFieldMap().get(field_name, [])
|
'Documents do not support iteration.
This is provided to raise an explicit exception.'
| def __iter__(self):
| raise TypeError('Documents do not support iteration.')
|
'Lazily build the field map.'
| def _BuildFieldMap(self):
| if (self._field_map is None):
self._field_map = {}
for field in self._fields:
self._field_map.setdefault(field.name, []).append(field)
return self._field_map
|
'Checks if rank is valid, then returns it.'
| def _CheckRank(self, rank):
| return _CheckInteger(rank, 'rank', upper_bound=sys.maxint)
|
'Returns a default rank as total seconds since 1st Jan 2011.'
| def _GetDefaultRank(self):
| td = (datetime.datetime.now() - Document._FIRST_JAN_2011)
return (td.seconds + ((td.days * 24) * 3600))
|
'Initializer.
Args:
name: The name of the computed field for the expression.
expression: The expression to evaluate and return in a field with
given name in results. See
https://developers.google.com/appengine/docs/python/search/overview#Expressions
for a list of legal expressions.
Raises:
TypeError: If any of the para... | def __init__(self, name, expression):
| self._name = _CheckFieldName(_ConvertToUnicode(name))
if (expression is None):
raise ValueError('expression must be a FieldExpression, got None')
if (not isinstance(expression, basestring)):
raise TypeError(('expression must be a FieldExpression, got %s' %... |
'Returns name of the expression to return in search results.'
| @property
def name(self):
| return self._name
|
'Returns a string containing an expression returned in search results.'
| @property
def expression(self):
| return self._expression
|
'Initializer.
Args:
expressions: An iterable of SortExpression representing a
multi-dimensional sort of Documents.
match_scorer: A match scorer specification which may be used to
score documents or in a SortExpression combined with other features.
limit: The limit on the number of documents to score or sort.
Raises:
Ty... | def __init__(self, expressions=None, match_scorer=None, limit=1000):
| self._match_scorer = match_scorer
self._expressions = _GetList(expressions)
for expression in self._expressions:
if (not isinstance(expression, SortExpression)):
raise TypeError(('expression must be a SortExpression, got %s' % expression.__class__.__name__))
self._l... |
'A list of SortExpression specifying a multi-dimensional sort.'
| @property
def expressions(self):
| return self._expressions
|
'Returns a match scorer to score documents with.'
| @property
def match_scorer(self):
| return self._match_scorer
|
'Returns the limit on the number of documents to score or sort.'
| @property
def limit(self):
| return self._limit
|
'Initializer.
Raises:
TypeError: If any of the parameters has an invalid type, or an unknown
attribute is passed.
ValueError: If any of the parameters has an invalid value.'
| def __init__(self):
| super(RescoringMatchScorer, self).__init__()
|
'Initializer.
Args:
expression: An expression to be evaluated on each matching document
to sort by. The expression must evaluate to a text or numeric value.
The expression can simply be a field name, or some compound expression
such as "_score + count(likes) * 0.1" which will add the score from a
scorer to a count of t... | def __init__(self, expression, direction=DESCENDING, default_value=''):
| self._expression = _ConvertToUnicode(expression)
self._direction = self._CheckDirection(direction)
if (self._expression is None):
raise TypeError('expression must be a SortExpression, got None')
_CheckExpression(self._expression)
self._default_value = default_value
if i... |
'Returns the expression to sort by.'
| @property
def expression(self):
| return self._expression
|
'Returns the direction to sort expression: ASCENDING or DESCENDING.'
| @property
def direction(self):
| return self._direction
|
'Returns a default value for the expression if no value computed.'
| @property
def default_value(self):
| return self._default_value
|
'Checks direction is a valid SortExpression direction and returns it.'
| def _CheckDirection(self, direction):
| return _CheckEnum(direction, 'direction', values=self._DIRECTIONS)
|
'Initializer.
Args:
doc_id: The visible printable ASCII string identifying the document which
does not start with \'!\'. Whitespace is excluded from ids. If no id is
provided, the search service will provide one.
fields: An iterable of Field instances representing the content of the
document.
language: The code of the ... | def __init__(self, doc_id=None, fields=None, language='en', sort_scores=None, expressions=None, cursor=None, rank=None):
| super(ScoredDocument, self).__init__(doc_id=doc_id, fields=fields, language=language, rank=rank)
self._sort_scores = self._CheckSortScores(_GetList(sort_scores))
self._expressions = _GetList(expressions)
if ((cursor is not None) and (not isinstance(cursor, Cursor))):
raise TypeError(('cursor ... |
'The list of scores assigned during sort evaluation.
Each sort dimension is included. Positive scores are used for ascending
sorts; negative scores for descending.
Returns:
The list of numeric sort scores.'
| @property
def sort_scores(self):
| return self._sort_scores
|
'The list of computed fields the result of expression evaluation.
For example, if a request has
FieldExpression(name=\'snippet\', \'snippet("good story", content)\')
meaning to compute a snippet field containing HTML snippets extracted
from the matching of the query \'good story\' on the field \'content\'.
This means a... | @property
def expressions(self):
| return self._expressions
|
'A cursor associated with a result, a continued search starting point.
To get this cursor to appear, set the Index.cursor_type to
Index.RESULT_CURSOR, otherwise this will be None.
Returns:
The result cursor.'
| @property
def cursor(self):
| return self._cursor
|
'Checks sort_scores is a list of floats, and returns it.'
| def _CheckSortScores(self, sort_scores):
| for sort_score in sort_scores:
_CheckNumber(sort_score, 'sort_scores')
return sort_scores
|
'Initializer.
Args:
number_found: The number of documents found for the query.
results: The list of ScoredDocuments returned from executing a
search request.
cursor: A Cursor to continue the search from the end of the
search results.
Raises:
TypeError: If any of the parameters have an invalid type, or an unknown
attrib... | def __init__(self, number_found, results=None, cursor=None):
| self._number_found = _CheckInteger(number_found, 'number_found')
self._results = _GetList(results)
if ((cursor is not None) and (not isinstance(cursor, Cursor))):
raise TypeError(('cursor must be a Cursor, got %s' % cursor.__class__.__name__))
self._cursor = cursor
|
'Returns the list of ScoredDocuments that matched the query.'
| @property
def results(self):
| return self._results
|
'Returns the number of documents which were found for the search.
Note that this is an approximation and not an exact count.
If QueryOptions.number_found_accuracy parameter is set to 100
for example, then number_found <= 100 is accurate.
Returns:
The number of documents found.'
| @property
def number_found(self):
| return self._number_found
|
'Returns a cursor that can be used to continue search from last result.
This corresponds to using a ResultsCursor in QueryOptions,
otherwise this will be None.
Returns:
The results cursor.'
| @property
def cursor(self):
| return self._cursor
|
'Initializer.
Args:
results: The results returned from an index ordered by Id.
Raises:
TypeError: If any of the parameters have an invalid type, or an unknown
attribute is passed.
ValueError: If any of the parameters have an invalid value.'
| def __init__(self, results=None):
| self._results = _GetList(results)
|
'Returns a list of results ordered by Id from the index.'
| @property
def results(self):
| return self._results
|
'Initializer.
Args:
web_safe_string: The cursor string returned from the search service to
be interpreted by the search service to get the next set of results.
per_result: A bool when true will return a cursor per ScoredDocument in
SearchResults, otherwise will return a single cursor for the whole
SearchResults. If usi... | def __init__(self, web_safe_string=None, per_result=False):
| self._web_safe_string = _CheckCursor(_ConvertToUnicode(web_safe_string))
self._per_result = per_result
if self._web_safe_string:
parts = self._web_safe_string.split(':', 1)
if ((len(parts) != 2) or (parts[0] not in ['True', 'False'])):
raise ValueError(('invalid format for ... |
'Returns the cursor string generated by the search service.'
| @property
def web_safe_string(self):
| return self._web_safe_string
|
'Returns whether to return a cursor for each ScoredDocument in results.'
| @property
def per_result(self):
| return self._per_result
|
'Initializer.
For example, the following code fragment requests a search for
documents where \'first\' occurs in subject and \'good\' occurs anywhere,
returning at most 20 documents, starting the search from \'cursor token\',
returning another single cursor for the SearchResults, sorting by subject in
descending order,... | def __init__(self, limit=20, number_found_accuracy=100, cursor=None, offset=None, sort_options=None, returned_fields=None, ids_only=False, snippeted_fields=None, returned_expressions=None):
| self._limit = _CheckLimit(limit)
self._number_found_accuracy = _CheckNumberFoundAccuracy(number_found_accuracy)
if ((cursor is not None) and (not isinstance(cursor, Cursor))):
raise TypeError(('cursor must be a Cursor, got %s' % cursor.__class__.__name__))
if ((cursor is not No... |
'Returns a limit on number of documents to return in results.'
| @property
def limit(self):
| return self._limit
|
'Returns minimum accuracy requirement for SearchResults.number_found.'
| @property
def number_found_accuracy(self):
| return self._number_found_accuracy
|
'Returns the Cursor for the query.'
| @property
def cursor(self):
| return self._cursor
|
'Returns the number of documents in search results to skip.'
| @property
def offset(self):
| return self._offset
|
'Returns a SortOptions.'
| @property
def sort_options(self):
| return self._sort_options
|
'Returns an iterable of names of fields to return in search results.'
| @property
def returned_fields(self):
| return self._returned_fields
|
'Returns whether to return only document ids in search results.'
| @property
def ids_only(self):
| return self._ids_only
|
'Returns iterable of field names to snippet and return in results.'
| @property
def snippeted_fields(self):
| return self._snippeted_fields
|
'Returns iterable of FieldExpression to return in results.'
| @property
def returned_expressions(self):
| return self._returned_expressions
|
'Initializer.
For example, the following code fragment requests a search for
documents where \'first\' occurs in subject and \'good\' occurs anywhere,
returning at most 20 documents, starting the search from \'cursor token\',
returning another single document cursor for the results, sorting by
subject in descending ord... | def __init__(self, query_string, options=None):
| self._query_string = _ConvertToUnicode(query_string)
_CheckQuery(self._query_string)
self._options = options
|
'Returns the query string to be applied to search service.'
| @property
def query_string(self):
| return self._query_string
|
'Returns QueryOptions defining post-processing on the search results.'
| @property
def options(self):
| return self._options
|
'Initializer.
Args:
name: The name of the index. An index name must be a visible printable
ASCII string not starting with \'!\'. Whitespace characters are excluded.
namespace: The namespace of the index name. If not set, then the current
namespace is used.
source: Deprecated as of 1.7.6. The source of
the index:
SEARCH... | def __init__(self, name, namespace=None, source=SEARCH):
| if (source not in self._SOURCES):
raise ValueError(('source must be one of %s' % self._SOURCES))
if (source is not self.SEARCH):
warnings.warn('source is deprecated.', DeprecationWarning, stacklevel=2)
self._source = source
self._name = _CheckIndexName(_ConvertToUnic... |
'Returns the schema mapping field names to list of types supported.
Only valid for Indexes returned by search.get_indexes method.'
| @property
def schema(self):
| return self._schema
|
'Returns the name of the index.'
| @property
def name(self):
| return self._name
|
'Returns the namespace of the name of the index.'
| @property
def namespace(self):
| return self._namespace
|
'Returns the source of the index.
Deprecated: from 1.7.6, source is no longer available.'
| @property
def source(self):
| warnings.warn('source is deprecated.', DeprecationWarning, stacklevel=2)
return self._source
|
'Constructs PutResult from RequestStatus pb and doc_id.'
| def _NewPutResultFromPb(self, status_pb, doc_id):
| message = None
if status_pb.has_error_detail():
message = _DecodeUTF8(status_pb.error_detail())
code = _ERROR_OPERATION_CODE_MAP[status_pb.code()]
return PutResult(code=code, message=message, id=_DecodeUTF8(doc_id))
|
'Index the collection of documents.
If any of the documents are already in the index, then reindex them with
their corresponding fresh document. If any of the documents fail to be
indexed, then none of the documents will be indexed.
Args:
documents: A Document or iterable of Documents to index.
Returns:
A list of PutRe... | def put(self, documents):
| if isinstance(documents, basestring):
raise TypeError(('documents must be a Document or sequence of Documents, got %s' % documents.__class__.__name__))
try:
docs = list(iter(documents))
except TypeError:
docs = [documents]
if (not docs):
retu... |
'Constructs DeleteResult from RequestStatus pb and doc_id.'
| def _NewDeleteResultFromPb(self, status_pb, doc_id):
| message = None
if status_pb.has_error_detail():
message = _DecodeUTF8(status_pb.error_detail())
code = _ERROR_OPERATION_CODE_MAP[status_pb.code()]
return DeleteResult(code=code, message=message, id=doc_id)
|
'Delete the documents with the corresponding document ids from the index.
If no document exists for the identifier in the list, then that document
identifier is ignored. If any document delete fails, then no documents
will be deleted.
Args:
document_ids: A single identifier or list of identifiers of documents
to delete... | def delete(self, document_ids):
| doc_ids = _ConvertToList(document_ids)
if (not doc_ids):
return
if (len(doc_ids) > MAXIMUM_DOCUMENTS_PER_PUT_REQUEST):
raise ValueError('too many documents to delete')
request = search_service_pb.DeleteDocumentRequest()
response = search_service_pb.DeleteDocumentResponse(... |
'Deprecated in 1.7.4. Delete the schema from the index.
We are deprecating this method and replacing with more general schema
and index managment.
A possible use may be remove typed fields which are no longer used. After
you delete the schema, you need to index one or more documents to rebuild
the schema. Until you re-... | def delete_schema(self):
| warnings.warn('delete_schema is deprecated in 1.7.4.', DeprecationWarning, stacklevel=2)
request = search_service_pb.DeleteSchemaRequest()
response = search_service_pb.DeleteSchemaResponse()
params = request.mutable_params()
_CopyMetadataToProtocolBuffer(self, params.add_index_spec())
... |
'Constructs a Document from a document_pb.Document protocol buffer.'
| def _NewScoredDocumentFromPb(self, doc_pb, sort_scores, expressions, cursor):
| lang = None
if doc_pb.has_language():
lang = _DecodeUTF8(doc_pb.language())
return ScoredDocument(doc_id=_DecodeUTF8(doc_pb.id()), fields=_NewFieldsFromPb(doc_pb.field_list()), language=lang, rank=doc_pb.order_id(), sort_scores=sort_scores, expressions=_NewFieldsFromPb(expressions), cursor=cursor)
|
'Returns a SearchResults populated from a search_service response pb.'
| def _NewSearchResults(self, response, cursor):
| results = []
for result_pb in response.result_list():
per_result_cursor = None
if result_pb.has_cursor():
if isinstance(cursor, Cursor):
per_result_cursor = Cursor(web_safe_string=_ToWebSafeString(cursor.per_result, _DecodeUTF8(result_pb.cursor())))
results.ap... |
'Retrieve a document by document ID.
Args:
doc_id: The ID of the document to retreive.
Returns:
If the document ID exists, returns the associated document. Otherwise,
returns None.'
| def get(self, doc_id):
| response = self.get_range(start_id=doc_id, limit=1)
if (response.results and (response.results[0].doc_id == doc_id)):
return response.results[0]
return None
|
'Search the index for documents matching the query.
For example, the following code fragment requests a search for
documents where \'first\' occurs in subject and \'good\' occurs anywhere,
returning at most 20 documents, starting the search from \'cursor token\',
returning another single cursor for the response, sortin... | def search(self, query, **kwargs):
| if ('app_id' in kwargs):
self._app_id = kwargs.pop('app_id')
else:
self._app_id = None
if kwargs:
raise TypeError(('Invalid arguments: %s' % ', '.join(kwargs)))
request = search_service_pb.SearchRequest()
if self._app_id:
request.set_app_id(self._app_id)
... |
'Returns a GetResponse from the list_documents response pb.'
| def _NewGetResponse(self, response):
| documents = []
for doc_proto in response.document_list():
documents.append(_NewDocumentFromPb(doc_proto))
return GetResponse(results=documents)
|
'Get a range of objects in the index, in id order in a response.'
| def _GetResponse(self, start_id=None, include_start_object=True, limit=100, ids_only=False, **kwargs):
| request = search_service_pb.ListDocumentsRequest()
if ('app_id' in kwargs):
request.set_app_id(kwargs.pop('app_id'))
if kwargs:
raise TypeError(('Invalid arguments: %s' % ', '.join(kwargs)))
params = request.mutable_params()
_CopyMetadataToProtocolBuffer(self, params.mutable... |
'Get a range of Documents in the index, in id order.
Args:
start_id: String containing the Id from which to list
Documents from. By default, starts at the first Id.
include_start_object: If true, include the Document with the
Id specified by the start_id parameter.
limit: The maximum number of Documents to return.
ids_... | def get_range(self, start_id=None, include_start_object=True, limit=100, ids_only=False, **kwargs):
| response = self._GetResponse(start_id=start_id, include_start_object=include_start_object, limit=limit, ids_only=ids_only, **kwargs)
return self._NewGetResponse(response)
|
'Raise an exception if the input fails to parse correctly.
Overriding the default, which normally just prints a message to
stderr.
Arguments:
msg: the error message
Raises:
QueryException: always.'
| def emitErrorMessage(self, msg):
| raise QueryException(msg)
|
'Raise an exception if the input fails to parse correctly.
Overriding the default, which normally just prints a message to
stderr.
Arguments:
msg: the error message
Raises:
QueryException: always.'
| def emitErrorMessage(self, msg):
| raise QueryException(msg)
|
'Tokenizes the text into a sequence of Tokens.'
| def TokenizeText(self, text, token_position=0):
| return self._TokenizeForType(field_type=document_pb.FieldValue.TEXT, value=text, token_position=token_position)
|
'Tokenizes a document_pb.FieldValue into a sequence of Tokens.'
| def TokenizeValue(self, field_value, token_position=0):
| if (field_value.type() == document_pb.FieldValue.GEO):
return self._TokenizeForType(field_type=field_value.type(), value=field_value.geo(), token_position=token_position)
return self._TokenizeForType(field_type=field_value.type(), value=field_value.string_value(), token_position=token_position)
|
'Replace HTML tags with spaces.'
| def _StripHtmlTags(self, value):
| return self._html_pattern.sub(' ', value)
|
'Tokenizes value into a sequence of Tokens.'
| def _TokenizeForType(self, field_type, value, token_position=0):
| if (field_type == document_pb.FieldValue.NUMBER):
return [tokens.Token(chars=value, position=token_position)]
if (field_type == document_pb.FieldValue.GEO):
return [tokens.GeoPoint(latitude=value.lat(), longitude=value.lng(), position=token_position)]
tokens_found = []
token_strings = []... |
'Constructor.
Args:
document: The ScoredDocument to evaluate the expression for.
inverted_index: The search index (used for snippeting).'
| def __init__(self, document, inverted_index):
| self._doc = document
self._doc_pb = document.document
self._inverted_index = inverted_index
self._tokenizer = simple_tokenizer.SimpleTokenizer(preserve_case=False)
self._case_preserving_tokenizer = simple_tokenizer.SimpleTokenizer(preserve_case=True)
self._function_table = {ExpressionParser.ABS:... |
'Generate a snippet that fills a given length from a list of tokens.
Args:
doc_words: A list of tokens from the document.
position: The index of the highlighted word.
max_length: The maximum length of the output snippet.
Returns:
A summary of the given words with the word at index position highlighted.'
| def _GenerateSnippet(self, doc_words, position, max_length):
| snippet = ('<b>%s</b>' % doc_words[position])
(next_len, prev_len) = (0, 0)
if ((position + 1) < len(doc_words)):
next_len = (len(doc_words[(position + 1)]) + 1)
if (position > 0):
prev_len = (len(doc_words[(position - 1)]) + 1)
i = 1
length_offset = (len(_SNIPPET_PREFIX) + len(_... |
'Create a snippet given a query and the field to query on.
Args:
query: A query string containing only a bare term (no operators).
field: The field name to query on.
*args: Unused optional arguments. These are not used on dev_appserver.
Returns:
A snippet for the field with the query term bolded.'
| def _Snippet(self, query, field, *args):
| field = query_parser.GetQueryNodeText(field)
terms = self._tokenizer.TokenizeText(query_parser.GetQueryNodeText(query).strip('"'))
for term in terms:
search_token = tokens.Token(chars=(u'%s:%s' % (field, term.chars)))
postings = self._inverted_index.GetPostingsForToken(search_token)
... |
'Returns a function that raises an unsupported error when called.
This should be used for methods that are not yet implemented in
dev_appserver but are present in the API. If users call this function, the
expression will be skipped and a warning will be logged.
Args:
method: The name of the method that was called (used... | def _Unsupported(self, method):
| def RaiseUnsupported(*args):
raise search_util.UnsupportedOnDevError(('%s is currently unsupported on dev_appserver.' % method))
return RaiseUnsupported
|
'Evaluate a binary operator on the document.
Args:
op: The operator function. Must take exactly two arguments.
op_name: The name of the operator. Used in error messages.
node: The expression AST node representing the operator application.
Returns:
The result of applying op to node\'s two children.
Raises:
ValueError: T... | def _EvalBinaryOp(self, op, op_name, node):
| if (len(node.children) != 2):
raise ValueError(('%s operator must always have two arguments' % op_name))
(n1, n2) = node.children
return op(self._Eval(n1), self._Eval(n2))
|
'Evaluate a unary operator on the document.
Args:
op: The operator function. Must take exactly one argument.
op_name: The name of the operator. Used in error messages.
node: The expression AST node representing the operator application.
Returns:
The result of applying op to node\'s child.
Raises:
ValueError: The node d... | def _EvalUnaryOp(self, op, op_name, node):
| if (len(node.children) != 1):
raise ValueError(('%s operator must always have one arguments' % op_name))
return op(self._Eval(node.children[0]))
|
'Evaluate an expression node on the document.
Args:
node: The expression AST node representing an expression subtree.
Returns:
The Python value that maps to the value of node. Types are inferred from
the expression, so expressions with numeric results will return as python
int/long/floats, textual results will be strin... | def _Eval(self, node):
| if (node.getType() in self._function_table):
func = self._function_table[node.getType()]
return func(*node.children)
if (node.getType() == ExpressionParser.PLUS):
return self._EvalBinaryOp((lambda a, b: (a + b)), 'addition', node)
if (node.getType() == ExpressionParser.MINUS):
... |
'Returns the value of an expression on a document.
Args:
expression: The expression string.
default_value: The value to return if the expression cannot be evaluated.
Returns:
The value of the expression on the evaluator\'s document, or default_value
if the expression cannot be evaluated on the document.'
| def ValueOf(self, expression, default_value=None):
| expression_tree = Parse(expression)
if ((not expression_tree.getType()) and expression_tree.children):
expression_tree = expression_tree.children[0]
result = default_value
try:
result = self._Eval(expression_tree)
except _ExpressionError as e:
logging.debug('Skipping expre... |
'Evaluates the expression for a document and attaches the result.
Args:
expression: The Expression protobuffer object.'
| def Evaluate(self, expression):
| name = expression.name()
result = self.ValueOf(expression.expression())
if (result != None):
self._doc.expressions[name] = result
|
'Returns the postings for the token.'
| def _PostingsForToken(self, token):
| return self._inverted_index.GetPostingsForToken(token)
|
'Returns postings for the value occurring in the given field.'
| def _PostingsForFieldToken(self, field, value):
| value = simple_tokenizer.NormalizeString(value)
return self._PostingsForToken(tokens.Token(chars=value, field_name=field))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.