图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1129 lines
37 KiB

  1. import itertools
  2. import time
  3. from typing import Dict, List, Optional, Union
  4. from redis.client import NEVER_DECODE, Pipeline
  5. from redis.utils import deprecated_function
  6. from ..helpers import get_protocol_version, parse_to_dict
  7. from ._util import to_string
  8. from .aggregation import AggregateRequest, AggregateResult, Cursor
  9. from .document import Document
  10. from .field import Field
  11. from .indexDefinition import IndexDefinition
  12. from .query import Query
  13. from .result import Result
  14. from .suggestion import SuggestionParser
  15. NUMERIC = "NUMERIC"
  16. CREATE_CMD = "FT.CREATE"
  17. ALTER_CMD = "FT.ALTER"
  18. SEARCH_CMD = "FT.SEARCH"
  19. ADD_CMD = "FT.ADD"
  20. ADDHASH_CMD = "FT.ADDHASH"
  21. DROP_CMD = "FT.DROP"
  22. DROPINDEX_CMD = "FT.DROPINDEX"
  23. EXPLAIN_CMD = "FT.EXPLAIN"
  24. EXPLAINCLI_CMD = "FT.EXPLAINCLI"
  25. DEL_CMD = "FT.DEL"
  26. AGGREGATE_CMD = "FT.AGGREGATE"
  27. PROFILE_CMD = "FT.PROFILE"
  28. CURSOR_CMD = "FT.CURSOR"
  29. SPELLCHECK_CMD = "FT.SPELLCHECK"
  30. DICT_ADD_CMD = "FT.DICTADD"
  31. DICT_DEL_CMD = "FT.DICTDEL"
  32. DICT_DUMP_CMD = "FT.DICTDUMP"
  33. GET_CMD = "FT.GET"
  34. MGET_CMD = "FT.MGET"
  35. CONFIG_CMD = "FT.CONFIG"
  36. TAGVALS_CMD = "FT.TAGVALS"
  37. ALIAS_ADD_CMD = "FT.ALIASADD"
  38. ALIAS_UPDATE_CMD = "FT.ALIASUPDATE"
  39. ALIAS_DEL_CMD = "FT.ALIASDEL"
  40. INFO_CMD = "FT.INFO"
  41. SUGADD_COMMAND = "FT.SUGADD"
  42. SUGDEL_COMMAND = "FT.SUGDEL"
  43. SUGLEN_COMMAND = "FT.SUGLEN"
  44. SUGGET_COMMAND = "FT.SUGGET"
  45. SYNUPDATE_CMD = "FT.SYNUPDATE"
  46. SYNDUMP_CMD = "FT.SYNDUMP"
  47. NOOFFSETS = "NOOFFSETS"
  48. NOFIELDS = "NOFIELDS"
  49. NOHL = "NOHL"
  50. NOFREQS = "NOFREQS"
  51. MAXTEXTFIELDS = "MAXTEXTFIELDS"
  52. TEMPORARY = "TEMPORARY"
  53. STOPWORDS = "STOPWORDS"
  54. SKIPINITIALSCAN = "SKIPINITIALSCAN"
  55. WITHSCORES = "WITHSCORES"
  56. FUZZY = "FUZZY"
  57. WITHPAYLOADS = "WITHPAYLOADS"
  58. class SearchCommands:
  59. """Search commands."""
  60. def _parse_results(self, cmd, res, **kwargs):
  61. if get_protocol_version(self.client) in ["3", 3]:
  62. return res
  63. else:
  64. return self._RESP2_MODULE_CALLBACKS[cmd](res, **kwargs)
  65. def _parse_info(self, res, **kwargs):
  66. it = map(to_string, res)
  67. return dict(zip(it, it))
  68. def _parse_search(self, res, **kwargs):
  69. return Result(
  70. res,
  71. not kwargs["query"]._no_content,
  72. duration=kwargs["duration"],
  73. has_payload=kwargs["query"]._with_payloads,
  74. with_scores=kwargs["query"]._with_scores,
  75. field_encodings=kwargs["query"]._return_fields_decode_as,
  76. )
  77. def _parse_aggregate(self, res, **kwargs):
  78. return self._get_aggregate_result(res, kwargs["query"], kwargs["has_cursor"])
  79. def _parse_profile(self, res, **kwargs):
  80. query = kwargs["query"]
  81. if isinstance(query, AggregateRequest):
  82. result = self._get_aggregate_result(res[0], query, query._cursor)
  83. else:
  84. result = Result(
  85. res[0],
  86. not query._no_content,
  87. duration=kwargs["duration"],
  88. has_payload=query._with_payloads,
  89. with_scores=query._with_scores,
  90. )
  91. return result, parse_to_dict(res[1])
  92. def _parse_spellcheck(self, res, **kwargs):
  93. corrections = {}
  94. if res == 0:
  95. return corrections
  96. for _correction in res:
  97. if isinstance(_correction, int) and _correction == 0:
  98. continue
  99. if len(_correction) != 3:
  100. continue
  101. if not _correction[2]:
  102. continue
  103. if not _correction[2][0]:
  104. continue
  105. # For spellcheck output
  106. # 1) 1) "TERM"
  107. # 2) "{term1}"
  108. # 3) 1) 1) "{score1}"
  109. # 2) "{suggestion1}"
  110. # 2) 1) "{score2}"
  111. # 2) "{suggestion2}"
  112. #
  113. # Following dictionary will be made
  114. # corrections = {
  115. # '{term1}': [
  116. # {'score': '{score1}', 'suggestion': '{suggestion1}'},
  117. # {'score': '{score2}', 'suggestion': '{suggestion2}'}
  118. # ]
  119. # }
  120. corrections[_correction[1]] = [
  121. {"score": _item[0], "suggestion": _item[1]} for _item in _correction[2]
  122. ]
  123. return corrections
  124. def _parse_config_get(self, res, **kwargs):
  125. return {kvs[0]: kvs[1] for kvs in res} if res else {}
  126. def _parse_syndump(self, res, **kwargs):
  127. return {res[i]: res[i + 1] for i in range(0, len(res), 2)}
  128. def batch_indexer(self, chunk_size=100):
  129. """
  130. Create a new batch indexer from the client with a given chunk size
  131. """
  132. return self.BatchIndexer(self, chunk_size=chunk_size)
  133. def create_index(
  134. self,
  135. fields: List[Field],
  136. no_term_offsets: bool = False,
  137. no_field_flags: bool = False,
  138. stopwords: Optional[List[str]] = None,
  139. definition: Optional[IndexDefinition] = None,
  140. max_text_fields=False,
  141. temporary=None,
  142. no_highlight: bool = False,
  143. no_term_frequencies: bool = False,
  144. skip_initial_scan: bool = False,
  145. ):
  146. """
  147. Creates the search index. The index must not already exist.
  148. For more information, see https://redis.io/commands/ft.create/
  149. Args:
  150. fields: A list of Field objects.
  151. no_term_offsets: If `true`, term offsets will not be saved in the index.
  152. no_field_flags: If true, field flags that allow searching in specific fields
  153. will not be saved.
  154. stopwords: If provided, the index will be created with this custom stopword
  155. list. The list can be empty.
  156. definition: If provided, the index will be created with this custom index
  157. definition.
  158. max_text_fields: If true, indexes will be encoded as if there were more than
  159. 32 text fields, allowing for additional fields beyond 32.
  160. temporary: Creates a lightweight temporary index which will expire after the
  161. specified period of inactivity. The internal idle timer is reset
  162. whenever the index is searched or added to.
  163. no_highlight: If true, disables highlighting support. Also implied by
  164. `no_term_offsets`.
  165. no_term_frequencies: If true, term frequencies will not be saved in the
  166. index.
  167. skip_initial_scan: If true, the initial scan and indexing will be skipped.
  168. """
  169. args = [CREATE_CMD, self.index_name]
  170. if definition is not None:
  171. args += definition.args
  172. if max_text_fields:
  173. args.append(MAXTEXTFIELDS)
  174. if temporary is not None and isinstance(temporary, int):
  175. args.append(TEMPORARY)
  176. args.append(temporary)
  177. if no_term_offsets:
  178. args.append(NOOFFSETS)
  179. if no_highlight:
  180. args.append(NOHL)
  181. if no_field_flags:
  182. args.append(NOFIELDS)
  183. if no_term_frequencies:
  184. args.append(NOFREQS)
  185. if skip_initial_scan:
  186. args.append(SKIPINITIALSCAN)
  187. if stopwords is not None and isinstance(stopwords, (list, tuple, set)):
  188. args += [STOPWORDS, len(stopwords)]
  189. if len(stopwords) > 0:
  190. args += list(stopwords)
  191. args.append("SCHEMA")
  192. try:
  193. args += list(itertools.chain(*(f.redis_args() for f in fields)))
  194. except TypeError:
  195. args += fields.redis_args()
  196. return self.execute_command(*args)
  197. def alter_schema_add(self, fields: List[str]):
  198. """
  199. Alter the existing search index by adding new fields. The index
  200. must already exist.
  201. ### Parameters:
  202. - **fields**: a list of Field objects to add for the index
  203. For more information see `FT.ALTER <https://redis.io/commands/ft.alter>`_.
  204. """ # noqa
  205. args = [ALTER_CMD, self.index_name, "SCHEMA", "ADD"]
  206. try:
  207. args += list(itertools.chain(*(f.redis_args() for f in fields)))
  208. except TypeError:
  209. args += fields.redis_args()
  210. return self.execute_command(*args)
  211. def dropindex(self, delete_documents: bool = False):
  212. """
  213. Drop the index if it exists.
  214. Replaced `drop_index` in RediSearch 2.0.
  215. Default behavior was changed to not delete the indexed documents.
  216. ### Parameters:
  217. - **delete_documents**: If `True`, all documents will be deleted.
  218. For more information see `FT.DROPINDEX <https://redis.io/commands/ft.dropindex>`_.
  219. """ # noqa
  220. delete_str = "DD" if delete_documents else ""
  221. return self.execute_command(DROPINDEX_CMD, self.index_name, delete_str)
  222. def _add_document(
  223. self,
  224. doc_id,
  225. conn=None,
  226. nosave=False,
  227. score=1.0,
  228. payload=None,
  229. replace=False,
  230. partial=False,
  231. language=None,
  232. no_create=False,
  233. **fields,
  234. ):
  235. """
  236. Internal add_document used for both batch and single doc indexing
  237. """
  238. if partial or no_create:
  239. replace = True
  240. args = [ADD_CMD, self.index_name, doc_id, score]
  241. if nosave:
  242. args.append("NOSAVE")
  243. if payload is not None:
  244. args.append("PAYLOAD")
  245. args.append(payload)
  246. if replace:
  247. args.append("REPLACE")
  248. if partial:
  249. args.append("PARTIAL")
  250. if no_create:
  251. args.append("NOCREATE")
  252. if language:
  253. args += ["LANGUAGE", language]
  254. args.append("FIELDS")
  255. args += list(itertools.chain(*fields.items()))
  256. if conn is not None:
  257. return conn.execute_command(*args)
  258. return self.execute_command(*args)
  259. def _add_document_hash(
  260. self, doc_id, conn=None, score=1.0, language=None, replace=False
  261. ):
  262. """
  263. Internal add_document_hash used for both batch and single doc indexing
  264. """
  265. args = [ADDHASH_CMD, self.index_name, doc_id, score]
  266. if replace:
  267. args.append("REPLACE")
  268. if language:
  269. args += ["LANGUAGE", language]
  270. if conn is not None:
  271. return conn.execute_command(*args)
  272. return self.execute_command(*args)
  273. @deprecated_function(
  274. version="2.0.0", reason="deprecated since redisearch 2.0, call hset instead"
  275. )
  276. def add_document(
  277. self,
  278. doc_id: str,
  279. nosave: bool = False,
  280. score: float = 1.0,
  281. payload: bool = None,
  282. replace: bool = False,
  283. partial: bool = False,
  284. language: Optional[str] = None,
  285. no_create: str = False,
  286. **fields: List[str],
  287. ):
  288. """
  289. Add a single document to the index.
  290. ### Parameters
  291. - **doc_id**: the id of the saved document.
  292. - **nosave**: if set to true, we just index the document, and don't
  293. save a copy of it. This means that searches will just
  294. return ids.
  295. - **score**: the document ranking, between 0.0 and 1.0
  296. - **payload**: optional inner-index payload we can save for fast
  297. i access in scoring functions
  298. - **replace**: if True, and the document already is in the index,
  299. we perform an update and reindex the document
  300. - **partial**: if True, the fields specified will be added to the
  301. existing document.
  302. This has the added benefit that any fields specified
  303. with `no_index`
  304. will not be reindexed again. Implies `replace`
  305. - **language**: Specify the language used for document tokenization.
  306. - **no_create**: if True, the document is only updated and reindexed
  307. if it already exists.
  308. If the document does not exist, an error will be
  309. returned. Implies `replace`
  310. - **fields** kwargs dictionary of the document fields to be saved
  311. and/or indexed.
  312. NOTE: Geo points shoule be encoded as strings of "lon,lat"
  313. """ # noqa
  314. return self._add_document(
  315. doc_id,
  316. conn=None,
  317. nosave=nosave,
  318. score=score,
  319. payload=payload,
  320. replace=replace,
  321. partial=partial,
  322. language=language,
  323. no_create=no_create,
  324. **fields,
  325. )
  326. @deprecated_function(
  327. version="2.0.0", reason="deprecated since redisearch 2.0, call hset instead"
  328. )
  329. def add_document_hash(self, doc_id, score=1.0, language=None, replace=False):
  330. """
  331. Add a hash document to the index.
  332. ### Parameters
  333. - **doc_id**: the document's id. This has to be an existing HASH key
  334. in Redis that will hold the fields the index needs.
  335. - **score**: the document ranking, between 0.0 and 1.0
  336. - **replace**: if True, and the document already is in the index, we
  337. perform an update and reindex the document
  338. - **language**: Specify the language used for document tokenization.
  339. """ # noqa
  340. return self._add_document_hash(
  341. doc_id, conn=None, score=score, language=language, replace=replace
  342. )
  343. def delete_document(self, doc_id, conn=None, delete_actual_document=False):
  344. """
  345. Delete a document from index
  346. Returns 1 if the document was deleted, 0 if not
  347. ### Parameters
  348. - **delete_actual_document**: if set to True, RediSearch also delete
  349. the actual document if it is in the index
  350. """ # noqa
  351. args = [DEL_CMD, self.index_name, doc_id]
  352. if delete_actual_document:
  353. args.append("DD")
  354. if conn is not None:
  355. return conn.execute_command(*args)
  356. return self.execute_command(*args)
  357. def load_document(self, id):
  358. """
  359. Load a single document by id
  360. """
  361. fields = self.client.hgetall(id)
  362. f2 = {to_string(k): to_string(v) for k, v in fields.items()}
  363. fields = f2
  364. try:
  365. del fields["id"]
  366. except KeyError:
  367. pass
  368. return Document(id=id, **fields)
  369. def get(self, *ids):
  370. """
  371. Returns the full contents of multiple documents.
  372. ### Parameters
  373. - **ids**: the ids of the saved documents.
  374. """
  375. return self.execute_command(MGET_CMD, self.index_name, *ids)
  376. def info(self):
  377. """
  378. Get info an stats about the the current index, including the number of
  379. documents, memory consumption, etc
  380. For more information see `FT.INFO <https://redis.io/commands/ft.info>`_.
  381. """
  382. res = self.execute_command(INFO_CMD, self.index_name)
  383. return self._parse_results(INFO_CMD, res)
  384. def get_params_args(
  385. self, query_params: Union[Dict[str, Union[str, int, float, bytes]], None]
  386. ):
  387. if query_params is None:
  388. return []
  389. args = []
  390. if len(query_params) > 0:
  391. args.append("params")
  392. args.append(len(query_params) * 2)
  393. for key, value in query_params.items():
  394. args.append(key)
  395. args.append(value)
  396. return args
  397. def _mk_query_args(
  398. self, query, query_params: Union[Dict[str, Union[str, int, float, bytes]], None]
  399. ):
  400. args = [self.index_name]
  401. if isinstance(query, str):
  402. # convert the query from a text to a query object
  403. query = Query(query)
  404. if not isinstance(query, Query):
  405. raise ValueError(f"Bad query type {type(query)}")
  406. args += query.get_args()
  407. args += self.get_params_args(query_params)
  408. return args, query
  409. def search(
  410. self,
  411. query: Union[str, Query],
  412. query_params: Union[Dict[str, Union[str, int, float, bytes]], None] = None,
  413. ):
  414. """
  415. Search the index for a given query, and return a result of documents
  416. ### Parameters
  417. - **query**: the search query. Either a text for simple queries with
  418. default parameters, or a Query object for complex queries.
  419. See RediSearch's documentation on query format
  420. For more information see `FT.SEARCH <https://redis.io/commands/ft.search>`_.
  421. """ # noqa
  422. args, query = self._mk_query_args(query, query_params=query_params)
  423. st = time.time()
  424. options = {}
  425. if get_protocol_version(self.client) not in ["3", 3]:
  426. options[NEVER_DECODE] = True
  427. res = self.execute_command(SEARCH_CMD, *args, **options)
  428. if isinstance(res, Pipeline):
  429. return res
  430. return self._parse_results(
  431. SEARCH_CMD, res, query=query, duration=(time.time() - st) * 1000.0
  432. )
  433. def explain(
  434. self,
  435. query: Union[str, Query],
  436. query_params: Dict[str, Union[str, int, float]] = None,
  437. ):
  438. """Returns the execution plan for a complex query.
  439. For more information see `FT.EXPLAIN <https://redis.io/commands/ft.explain>`_.
  440. """ # noqa
  441. args, query_text = self._mk_query_args(query, query_params=query_params)
  442. return self.execute_command(EXPLAIN_CMD, *args)
  443. def explain_cli(self, query: Union[str, Query]): # noqa
  444. raise NotImplementedError("EXPLAINCLI will not be implemented.")
  445. def aggregate(
  446. self,
  447. query: Union[str, Query],
  448. query_params: Dict[str, Union[str, int, float]] = None,
  449. ):
  450. """
  451. Issue an aggregation query.
  452. ### Parameters
  453. **query**: This can be either an `AggregateRequest`, or a `Cursor`
  454. An `AggregateResult` object is returned. You can access the rows from
  455. its `rows` property, which will always yield the rows of the result.
  456. For more information see `FT.AGGREGATE <https://redis.io/commands/ft.aggregate>`_.
  457. """ # noqa
  458. if isinstance(query, AggregateRequest):
  459. has_cursor = bool(query._cursor)
  460. cmd = [AGGREGATE_CMD, self.index_name] + query.build_args()
  461. elif isinstance(query, Cursor):
  462. has_cursor = True
  463. cmd = [CURSOR_CMD, "READ", self.index_name] + query.build_args()
  464. else:
  465. raise ValueError("Bad query", query)
  466. cmd += self.get_params_args(query_params)
  467. raw = self.execute_command(*cmd)
  468. return self._parse_results(
  469. AGGREGATE_CMD, raw, query=query, has_cursor=has_cursor
  470. )
  471. def _get_aggregate_result(
  472. self, raw: List, query: Union[str, Query, AggregateRequest], has_cursor: bool
  473. ):
  474. if has_cursor:
  475. if isinstance(query, Cursor):
  476. query.cid = raw[1]
  477. cursor = query
  478. else:
  479. cursor = Cursor(raw[1])
  480. raw = raw[0]
  481. else:
  482. cursor = None
  483. if isinstance(query, AggregateRequest) and query._with_schema:
  484. schema = raw[0]
  485. rows = raw[2:]
  486. else:
  487. schema = None
  488. rows = raw[1:]
  489. return AggregateResult(rows, cursor, schema)
  490. def profile(
  491. self,
  492. query: Union[str, Query, AggregateRequest],
  493. limited: bool = False,
  494. query_params: Optional[Dict[str, Union[str, int, float]]] = None,
  495. ):
  496. """
  497. Performs a search or aggregate command and collects performance
  498. information.
  499. ### Parameters
  500. **query**: This can be either an `AggregateRequest`, `Query` or string.
  501. **limited**: If set to True, removes details of reader iterator.
  502. **query_params**: Define one or more value parameters.
  503. Each parameter has a name and a value.
  504. """
  505. st = time.time()
  506. cmd = [PROFILE_CMD, self.index_name, ""]
  507. if limited:
  508. cmd.append("LIMITED")
  509. cmd.append("QUERY")
  510. if isinstance(query, AggregateRequest):
  511. cmd[2] = "AGGREGATE"
  512. cmd += query.build_args()
  513. elif isinstance(query, Query):
  514. cmd[2] = "SEARCH"
  515. cmd += query.get_args()
  516. cmd += self.get_params_args(query_params)
  517. else:
  518. raise ValueError("Must provide AggregateRequest object or Query object.")
  519. res = self.execute_command(*cmd)
  520. return self._parse_results(
  521. PROFILE_CMD, res, query=query, duration=(time.time() - st) * 1000.0
  522. )
  523. def spellcheck(self, query, distance=None, include=None, exclude=None):
  524. """
  525. Issue a spellcheck query
  526. ### Parameters
  527. **query**: search query.
  528. **distance***: the maximal Levenshtein distance for spelling
  529. suggestions (default: 1, max: 4).
  530. **include**: specifies an inclusion custom dictionary.
  531. **exclude**: specifies an exclusion custom dictionary.
  532. For more information see `FT.SPELLCHECK <https://redis.io/commands/ft.spellcheck>`_.
  533. """ # noqa
  534. cmd = [SPELLCHECK_CMD, self.index_name, query]
  535. if distance:
  536. cmd.extend(["DISTANCE", distance])
  537. if include:
  538. cmd.extend(["TERMS", "INCLUDE", include])
  539. if exclude:
  540. cmd.extend(["TERMS", "EXCLUDE", exclude])
  541. res = self.execute_command(*cmd)
  542. return self._parse_results(SPELLCHECK_CMD, res)
  543. def dict_add(self, name: str, *terms: List[str]):
  544. """Adds terms to a dictionary.
  545. ### Parameters
  546. - **name**: Dictionary name.
  547. - **terms**: List of items for adding to the dictionary.
  548. For more information see `FT.DICTADD <https://redis.io/commands/ft.dictadd>`_.
  549. """ # noqa
  550. cmd = [DICT_ADD_CMD, name]
  551. cmd.extend(terms)
  552. return self.execute_command(*cmd)
  553. def dict_del(self, name: str, *terms: List[str]):
  554. """Deletes terms from a dictionary.
  555. ### Parameters
  556. - **name**: Dictionary name.
  557. - **terms**: List of items for removing from the dictionary.
  558. For more information see `FT.DICTDEL <https://redis.io/commands/ft.dictdel>`_.
  559. """ # noqa
  560. cmd = [DICT_DEL_CMD, name]
  561. cmd.extend(terms)
  562. return self.execute_command(*cmd)
  563. def dict_dump(self, name: str):
  564. """Dumps all terms in the given dictionary.
  565. ### Parameters
  566. - **name**: Dictionary name.
  567. For more information see `FT.DICTDUMP <https://redis.io/commands/ft.dictdump>`_.
  568. """ # noqa
  569. cmd = [DICT_DUMP_CMD, name]
  570. return self.execute_command(*cmd)
  571. def config_set(self, option: str, value: str) -> bool:
  572. """Set runtime configuration option.
  573. ### Parameters
  574. - **option**: the name of the configuration option.
  575. - **value**: a value for the configuration option.
  576. For more information see `FT.CONFIG SET <https://redis.io/commands/ft.config-set>`_.
  577. """ # noqa
  578. cmd = [CONFIG_CMD, "SET", option, value]
  579. raw = self.execute_command(*cmd)
  580. return raw == "OK"
  581. def config_get(self, option: str) -> str:
  582. """Get runtime configuration option value.
  583. ### Parameters
  584. - **option**: the name of the configuration option.
  585. For more information see `FT.CONFIG GET <https://redis.io/commands/ft.config-get>`_.
  586. """ # noqa
  587. cmd = [CONFIG_CMD, "GET", option]
  588. res = self.execute_command(*cmd)
  589. return self._parse_results(CONFIG_CMD, res)
  590. def tagvals(self, tagfield: str):
  591. """
  592. Return a list of all possible tag values
  593. ### Parameters
  594. - **tagfield**: Tag field name
  595. For more information see `FT.TAGVALS <https://redis.io/commands/ft.tagvals>`_.
  596. """ # noqa
  597. return self.execute_command(TAGVALS_CMD, self.index_name, tagfield)
  598. def aliasadd(self, alias: str):
  599. """
  600. Alias a search index - will fail if alias already exists
  601. ### Parameters
  602. - **alias**: Name of the alias to create
  603. For more information see `FT.ALIASADD <https://redis.io/commands/ft.aliasadd>`_.
  604. """ # noqa
  605. return self.execute_command(ALIAS_ADD_CMD, alias, self.index_name)
  606. def aliasupdate(self, alias: str):
  607. """
  608. Updates an alias - will fail if alias does not already exist
  609. ### Parameters
  610. - **alias**: Name of the alias to create
  611. For more information see `FT.ALIASUPDATE <https://redis.io/commands/ft.aliasupdate>`_.
  612. """ # noqa
  613. return self.execute_command(ALIAS_UPDATE_CMD, alias, self.index_name)
  614. def aliasdel(self, alias: str):
  615. """
  616. Removes an alias to a search index
  617. ### Parameters
  618. - **alias**: Name of the alias to delete
  619. For more information see `FT.ALIASDEL <https://redis.io/commands/ft.aliasdel>`_.
  620. """ # noqa
  621. return self.execute_command(ALIAS_DEL_CMD, alias)
  622. def sugadd(self, key, *suggestions, **kwargs):
  623. """
  624. Add suggestion terms to the AutoCompleter engine. Each suggestion has
  625. a score and string.
  626. If kwargs["increment"] is true and the terms are already in the
  627. server's dictionary, we increment their scores.
  628. For more information see `FT.SUGADD <https://redis.io/commands/ft.sugadd/>`_.
  629. """ # noqa
  630. # If Transaction is not False it will MULTI/EXEC which will error
  631. pipe = self.pipeline(transaction=False)
  632. for sug in suggestions:
  633. args = [SUGADD_COMMAND, key, sug.string, sug.score]
  634. if kwargs.get("increment"):
  635. args.append("INCR")
  636. if sug.payload:
  637. args.append("PAYLOAD")
  638. args.append(sug.payload)
  639. pipe.execute_command(*args)
  640. return pipe.execute()[-1]
  641. def suglen(self, key: str) -> int:
  642. """
  643. Return the number of entries in the AutoCompleter index.
  644. For more information see `FT.SUGLEN <https://redis.io/commands/ft.suglen>`_.
  645. """ # noqa
  646. return self.execute_command(SUGLEN_COMMAND, key)
  647. def sugdel(self, key: str, string: str) -> int:
  648. """
  649. Delete a string from the AutoCompleter index.
  650. Returns 1 if the string was found and deleted, 0 otherwise.
  651. For more information see `FT.SUGDEL <https://redis.io/commands/ft.sugdel>`_.
  652. """ # noqa
  653. return self.execute_command(SUGDEL_COMMAND, key, string)
  654. def sugget(
  655. self,
  656. key: str,
  657. prefix: str,
  658. fuzzy: bool = False,
  659. num: int = 10,
  660. with_scores: bool = False,
  661. with_payloads: bool = False,
  662. ) -> List[SuggestionParser]:
  663. """
  664. Get a list of suggestions from the AutoCompleter, for a given prefix.
  665. Parameters:
  666. prefix : str
  667. The prefix we are searching. **Must be valid ascii or utf-8**
  668. fuzzy : bool
  669. If set to true, the prefix search is done in fuzzy mode.
  670. **NOTE**: Running fuzzy searches on short (<3 letters) prefixes
  671. can be very
  672. slow, and even scan the entire index.
  673. with_scores : bool
  674. If set to true, we also return the (refactored) score of
  675. each suggestion.
  676. This is normally not needed, and is NOT the original score
  677. inserted into the index.
  678. with_payloads : bool
  679. Return suggestion payloads
  680. num : int
  681. The maximum number of results we return. Note that we might
  682. return less. The algorithm trims irrelevant suggestions.
  683. Returns:
  684. list:
  685. A list of Suggestion objects. If with_scores was False, the
  686. score of all suggestions is 1.
  687. For more information see `FT.SUGGET <https://redis.io/commands/ft.sugget>`_.
  688. """ # noqa
  689. args = [SUGGET_COMMAND, key, prefix, "MAX", num]
  690. if fuzzy:
  691. args.append(FUZZY)
  692. if with_scores:
  693. args.append(WITHSCORES)
  694. if with_payloads:
  695. args.append(WITHPAYLOADS)
  696. res = self.execute_command(*args)
  697. results = []
  698. if not res:
  699. return results
  700. parser = SuggestionParser(with_scores, with_payloads, res)
  701. return [s for s in parser]
  702. def synupdate(self, groupid: str, skipinitial: bool = False, *terms: List[str]):
  703. """
  704. Updates a synonym group.
  705. The command is used to create or update a synonym group with
  706. additional terms.
  707. Only documents which were indexed after the update will be affected.
  708. Parameters:
  709. groupid :
  710. Synonym group id.
  711. skipinitial : bool
  712. If set to true, we do not scan and index.
  713. terms :
  714. The terms.
  715. For more information see `FT.SYNUPDATE <https://redis.io/commands/ft.synupdate>`_.
  716. """ # noqa
  717. cmd = [SYNUPDATE_CMD, self.index_name, groupid]
  718. if skipinitial:
  719. cmd.extend(["SKIPINITIALSCAN"])
  720. cmd.extend(terms)
  721. return self.execute_command(*cmd)
  722. def syndump(self):
  723. """
  724. Dumps the contents of a synonym group.
  725. The command is used to dump the synonyms data structure.
  726. Returns a list of synonym terms and their synonym group ids.
  727. For more information see `FT.SYNDUMP <https://redis.io/commands/ft.syndump>`_.
  728. """ # noqa
  729. res = self.execute_command(SYNDUMP_CMD, self.index_name)
  730. return self._parse_results(SYNDUMP_CMD, res)
  731. class AsyncSearchCommands(SearchCommands):
  732. async def info(self):
  733. """
  734. Get info an stats about the the current index, including the number of
  735. documents, memory consumption, etc
  736. For more information see `FT.INFO <https://redis.io/commands/ft.info>`_.
  737. """
  738. res = await self.execute_command(INFO_CMD, self.index_name)
  739. return self._parse_results(INFO_CMD, res)
  740. async def search(
  741. self,
  742. query: Union[str, Query],
  743. query_params: Dict[str, Union[str, int, float]] = None,
  744. ):
  745. """
  746. Search the index for a given query, and return a result of documents
  747. ### Parameters
  748. - **query**: the search query. Either a text for simple queries with
  749. default parameters, or a Query object for complex queries.
  750. See RediSearch's documentation on query format
  751. For more information see `FT.SEARCH <https://redis.io/commands/ft.search>`_.
  752. """ # noqa
  753. args, query = self._mk_query_args(query, query_params=query_params)
  754. st = time.time()
  755. options = {}
  756. if get_protocol_version(self.client) not in ["3", 3]:
  757. options[NEVER_DECODE] = True
  758. res = await self.execute_command(SEARCH_CMD, *args, **options)
  759. if isinstance(res, Pipeline):
  760. return res
  761. return self._parse_results(
  762. SEARCH_CMD, res, query=query, duration=(time.time() - st) * 1000.0
  763. )
  764. async def aggregate(
  765. self,
  766. query: Union[str, Query],
  767. query_params: Dict[str, Union[str, int, float]] = None,
  768. ):
  769. """
  770. Issue an aggregation query.
  771. ### Parameters
  772. **query**: This can be either an `AggregateRequest`, or a `Cursor`
  773. An `AggregateResult` object is returned. You can access the rows from
  774. its `rows` property, which will always yield the rows of the result.
  775. For more information see `FT.AGGREGATE <https://redis.io/commands/ft.aggregate>`_.
  776. """ # noqa
  777. if isinstance(query, AggregateRequest):
  778. has_cursor = bool(query._cursor)
  779. cmd = [AGGREGATE_CMD, self.index_name] + query.build_args()
  780. elif isinstance(query, Cursor):
  781. has_cursor = True
  782. cmd = [CURSOR_CMD, "READ", self.index_name] + query.build_args()
  783. else:
  784. raise ValueError("Bad query", query)
  785. cmd += self.get_params_args(query_params)
  786. raw = await self.execute_command(*cmd)
  787. return self._parse_results(
  788. AGGREGATE_CMD, raw, query=query, has_cursor=has_cursor
  789. )
  790. async def spellcheck(self, query, distance=None, include=None, exclude=None):
  791. """
  792. Issue a spellcheck query
  793. ### Parameters
  794. **query**: search query.
  795. **distance***: the maximal Levenshtein distance for spelling
  796. suggestions (default: 1, max: 4).
  797. **include**: specifies an inclusion custom dictionary.
  798. **exclude**: specifies an exclusion custom dictionary.
  799. For more information see `FT.SPELLCHECK <https://redis.io/commands/ft.spellcheck>`_.
  800. """ # noqa
  801. cmd = [SPELLCHECK_CMD, self.index_name, query]
  802. if distance:
  803. cmd.extend(["DISTANCE", distance])
  804. if include:
  805. cmd.extend(["TERMS", "INCLUDE", include])
  806. if exclude:
  807. cmd.extend(["TERMS", "EXCLUDE", exclude])
  808. res = await self.execute_command(*cmd)
  809. return self._parse_results(SPELLCHECK_CMD, res)
  810. async def config_set(self, option: str, value: str) -> bool:
  811. """Set runtime configuration option.
  812. ### Parameters
  813. - **option**: the name of the configuration option.
  814. - **value**: a value for the configuration option.
  815. For more information see `FT.CONFIG SET <https://redis.io/commands/ft.config-set>`_.
  816. """ # noqa
  817. cmd = [CONFIG_CMD, "SET", option, value]
  818. raw = await self.execute_command(*cmd)
  819. return raw == "OK"
  820. async def config_get(self, option: str) -> str:
  821. """Get runtime configuration option value.
  822. ### Parameters
  823. - **option**: the name of the configuration option.
  824. For more information see `FT.CONFIG GET <https://redis.io/commands/ft.config-get>`_.
  825. """ # noqa
  826. cmd = [CONFIG_CMD, "GET", option]
  827. res = {}
  828. res = await self.execute_command(*cmd)
  829. return self._parse_results(CONFIG_CMD, res)
  830. async def load_document(self, id):
  831. """
  832. Load a single document by id
  833. """
  834. fields = await self.client.hgetall(id)
  835. f2 = {to_string(k): to_string(v) for k, v in fields.items()}
  836. fields = f2
  837. try:
  838. del fields["id"]
  839. except KeyError:
  840. pass
  841. return Document(id=id, **fields)
  842. async def sugadd(self, key, *suggestions, **kwargs):
  843. """
  844. Add suggestion terms to the AutoCompleter engine. Each suggestion has
  845. a score and string.
  846. If kwargs["increment"] is true and the terms are already in the
  847. server's dictionary, we increment their scores.
  848. For more information see `FT.SUGADD <https://redis.io/commands/ft.sugadd>`_.
  849. """ # noqa
  850. # If Transaction is not False it will MULTI/EXEC which will error
  851. pipe = self.pipeline(transaction=False)
  852. for sug in suggestions:
  853. args = [SUGADD_COMMAND, key, sug.string, sug.score]
  854. if kwargs.get("increment"):
  855. args.append("INCR")
  856. if sug.payload:
  857. args.append("PAYLOAD")
  858. args.append(sug.payload)
  859. pipe.execute_command(*args)
  860. return (await pipe.execute())[-1]
  861. async def sugget(
  862. self,
  863. key: str,
  864. prefix: str,
  865. fuzzy: bool = False,
  866. num: int = 10,
  867. with_scores: bool = False,
  868. with_payloads: bool = False,
  869. ) -> List[SuggestionParser]:
  870. """
  871. Get a list of suggestions from the AutoCompleter, for a given prefix.
  872. Parameters:
  873. prefix : str
  874. The prefix we are searching. **Must be valid ascii or utf-8**
  875. fuzzy : bool
  876. If set to true, the prefix search is done in fuzzy mode.
  877. **NOTE**: Running fuzzy searches on short (<3 letters) prefixes
  878. can be very
  879. slow, and even scan the entire index.
  880. with_scores : bool
  881. If set to true, we also return the (refactored) score of
  882. each suggestion.
  883. This is normally not needed, and is NOT the original score
  884. inserted into the index.
  885. with_payloads : bool
  886. Return suggestion payloads
  887. num : int
  888. The maximum number of results we return. Note that we might
  889. return less. The algorithm trims irrelevant suggestions.
  890. Returns:
  891. list:
  892. A list of Suggestion objects. If with_scores was False, the
  893. score of all suggestions is 1.
  894. For more information see `FT.SUGGET <https://redis.io/commands/ft.sugget>`_.
  895. """ # noqa
  896. args = [SUGGET_COMMAND, key, prefix, "MAX", num]
  897. if fuzzy:
  898. args.append(FUZZY)
  899. if with_scores:
  900. args.append(WITHSCORES)
  901. if with_payloads:
  902. args.append(WITHPAYLOADS)
  903. ret = await self.execute_command(*args)
  904. results = []
  905. if not ret:
  906. return results
  907. parser = SuggestionParser(with_scores, with_payloads, ret)
  908. return [s for s in parser]