search.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """
  2. Sonic search backend - search and flush operations.
  3. This module provides the search interface for the Sonic backend.
  4. """
  5. import os
  6. from typing import List, Iterable
  7. def get_sonic_config() -> dict:
  8. """Get Sonic connection configuration."""
  9. return {
  10. 'host': os.environ.get('SEARCH_BACKEND_HOST_NAME', '127.0.0.1').strip(),
  11. 'port': int(os.environ.get('SEARCH_BACKEND_PORT', '1491')),
  12. 'password': os.environ.get('SEARCH_BACKEND_PASSWORD', 'SecretPassword').strip(),
  13. 'collection': os.environ.get('SONIC_COLLECTION', 'archivebox').strip(),
  14. 'bucket': os.environ.get('SONIC_BUCKET', 'snapshots').strip(),
  15. }
  16. def search(query: str) -> List[str]:
  17. """Search for snapshots in Sonic."""
  18. try:
  19. from sonic import SearchClient
  20. except ImportError:
  21. raise RuntimeError('sonic-client not installed. Run: pip install sonic-client')
  22. config = get_sonic_config()
  23. with SearchClient(config['host'], config['port'], config['password']) as search_client:
  24. results = search_client.query(config['collection'], config['bucket'], query, limit=100)
  25. return results
  26. def flush(snapshot_ids: Iterable[str]) -> None:
  27. """Remove snapshots from Sonic index."""
  28. try:
  29. from sonic import IngestClient
  30. except ImportError:
  31. raise RuntimeError('sonic-client not installed. Run: pip install sonic-client')
  32. config = get_sonic_config()
  33. with IngestClient(config['host'], config['port'], config['password']) as ingest:
  34. for snapshot_id in snapshot_ids:
  35. try:
  36. ingest.flush_object(config['collection'], config['bucket'], snapshot_id)
  37. except Exception:
  38. pass