Search

Nextcloud 20 offers a new unified search. The overall idea is to have one combined view for search, but have results of any data source displayed there. Hence this is logic is built on a pluggable architecture where apps register their search providers.

Concept overview

The unified search combines a variable number of search providers into a unified search result for the user. To improve the user experience with search, the search results should be displayed quickly. Therefore parallelism is used to split the process into several requests that can be processed concurrently, to give the client (e.g. JavaScript in the browser) the ability to display partial search results as they come on.

Hence the search process consists of two steps.

  1. Fetch the current set of search provider IDs
  2. Fetch each provider’s search results

These two steps have to be run consecutively, but the individual requests in the second step can be dispatched and processed concurrently.

Fetching provider IDs

GET https://cloud.domain/ocs/v2.php/search/providers

This will return a structure like

  1. {
  2. "ocs": {
  3. "meta": {
  4. },
  5. "data": [
  6. {
  7. "id": "mail",
  8. "name": "Mail",
  9. "order": -50
  10. },
  11. {
  12. "id": "files",
  13. "name": "Files",
  14. "order": 5
  15. }
  16. ]
  17. }
  18. }

Fetching individual search results

GET https://cloud.domain/ocs/v2.php/search/providers/files/search?term=cat

  1. {
  2. "ocs": {
  3. "meta": {
  4. },
  5. "data": {
  6. "name": "Files",
  7. "isPaginated": false,
  8. "entries": [
  9. {
  10. "thumbnailUrl": "/core/preview?x=32&y=32&fileId=9261",
  11. "title": "my cute cats.jpg",
  12. "subline": "/my cute cats.jpg",
  13. "resourceUrl": "/apps/files/?dir=/&scrollto=my%20cute%20cats.jpg"
  14. },
  15. {
  16. "thumbnailUrl": "/core/preview?x=32&y=32&fileId=1553",
  17. "title": "cat (2).png",
  18. "subline": "/cat (2).png",
  19. "resourceUrl": "/apps/files/?dir=/&scrollto=cat%20%282%29.png"
  20. }
  21. ],
  22. "cursor": null
  23. }
  24. }
  25. }

Search providers

A search provider is a class the implements the interface \OCP\Search\IProvider.

  1. <?php
  2. declare(strict_types=1);
  3. namespace OCA\MyApp\Search;
  4. use OCA\MyApp\AppInfo\Application;
  5. use OCP\IUser;
  6. use OCP\Search\IProvider;
  7. class Provider implements IProvider {
  8. public function getId(): string {
  9. return 'mysearchprovider';
  10. }
  11. public function getName(): string {
  12. return $this->l->t('My custom group');
  13. }
  14. public function getOrder(string $route, array $routeParameters): int {
  15. if (strpos($route, Application::APP_ID . '.') === 0) {
  16. // Active app, prefer my results
  17. return -1;
  18. }
  19. return 55;
  20. }
  21. public function search(IUser $user, ISearchQuery $query): SearchResult {
  22. return SearchResult::complete(
  23. 'My custom group', // TODO: this should be translated
  24. [
  25. ...
  26. ]
  27. );
  28. }
  29. }

The method getId returns a string identifier of the registered provider. It has to be globally unique, hence must not conflict with any other apps. Therefore it’s advised to use just the app ID (e.g. mail) as ID or an ID that is prefixed with the app id, like mail_recipients. getName is a translated name for your search results.

The getOrder method returns the order of the provider for the current page. With the route parameter you can check if the route is from your app and in that case use a negative value. Otherwise your app should use a value around 50.

The method search transforms a search request into a search result.

The class would typically be saved into a file in lib/Search of your app but you are free to put it elsewhere as long as it’s loadable by Nextcloud’s dependency injection container.

Provider registration

The provider class is registered via the bootstrap mechanism of the Application class.

  1. <?php
  2. declare(strict_types=1);
  3. namespace OCA\MyApp\AppInfo;
  4. use OCA\MyApp\Search\Provider;
  5. use OCP\AppFramework\App;
  6. use OCP\AppFramework\Bootstrap\IBootContext;
  7. use OCP\AppFramework\Bootstrap\IBootstrap;
  8. use OCP\AppFramework\Bootstrap\IRegistrationContext;
  9. class Application extends App implements IBootstrap {
  10. public function register(IRegistrationContext $context): void {
  11. $context->registerSearchProvider(Provider::class);
  12. }
  13. public function boot(IBootContext $context): void {}
  14. }

Handling search requests

Search requests are processed in the search method. The $user object is the user who the result shall be generated for. $query gives context information like the search term, the sort order, the route information, the size limit of a request and the cursor for follow-up request of paginated results.

The result is encapsulated in the SearchResult class that offers two static factory methods complete and paginated. Both of these methods take an array of SearchResultEntry objects.

Next, you’ll see a dummy provider that returns a static set of results.

  1. <?php
  2. declare(strict_types=1);
  3. namespace OCA\MyApp\Search;
  4. use OCA\MyApp\AppInfo\Application;
  5. use OCP\IL10N;
  6. use OCP\IURLGenerator;
  7. use OCP\IUser;
  8. use OCP\Search\IProvider;
  9. use OCP\Search\SearchResultEntry;
  10. class Provider implements IProvider {
  11. /** @var IL10N */
  12. private $l10n;
  13. /** @var IURLGenerator */
  14. private $urlGenerator;
  15. public function __construct(IL10N $l10n,
  16. IURLGenerator $urlGenerator) {
  17. $this->l10n = $l10n;
  18. $this->urlGenerator = $urlGenerator;
  19. }
  20. public function getId(): string {
  21. return 'mysearchprovider';
  22. }
  23. public function getName(): string {
  24. return $this->l->t('My app');
  25. }
  26. public function getOrder(string $route, array $routeParameters): int {
  27. if (strpos($route, Application::APP_ID . '.') === 0) {
  28. // Active app, prefer my results
  29. return -1;
  30. }
  31. return 25;
  32. }
  33. public function search(IUser $user, ISearchQuery $query): SearchResult {
  34. return SearchResult::complete(
  35. $this->l10n->t('My app'),
  36. [
  37. new SearchResultEntry(
  38. $this->urlGenerator->linkToRoute(
  39. 'myapp.Preview.getPreviewByFileId',
  40. [
  41. 'id' => 1
  42. ]
  43. ),
  44. 'Search result 1',
  45. 'This goes into the subline',
  46. $this->urlGenerator->linkToRoute(
  47. 'myapp.view.index',
  48. [
  49. 'id' => 1,
  50. ]
  51. )
  52. )
  53. ]
  54. );
  55. }
  56. }

Each of the result result entries has

  • A thumbnail or icon that is a (relative) URL
  • A title, e.g. the name of a file
  • A subline, e.g. the path to a file
  • A resource URL that makes it possible to navigate to the details of this result
  • Optional icon CSS class that is applied then the thumbnail URL was not set
  • A boolean rounded, whether the thumbnail should be rounded, e.g. when it’s an avatar

Apps may return the full result in search, but in most cases the size of the result set can become too big to fit into one HTTP request and is complicated to display to the user, hence the set should be split into chunks – it should be paginated.

Pagination

Paginated results work almost like complete results. The differences are that the SearchResult::paginated factory method is used to build the set and that you need a cursor for this.

There are two ways to use the cursor: offset-based pagination and cursor-based pagination.

For offset-based pagination you return $query->getLimit() results and specify this number as cursor. Any subsequent call where $query->getCursor() does not return null you take the value as offset for the next page. The following example shall demonstrate this use case.

  1. <?php
  2. declare(strict_types=1);
  3. namespace OCA\MyApp\Search;
  4. use OCA\MyApp\AppInfo\Application;
  5. use OCP\IL10N;
  6. use OCP\IURLGenerator;
  7. use OCP\IUser;
  8. use OCP\Search\IProvider;
  9. use OCP\Search\SearchResult;
  10. class Provider implements IProvider {
  11. /** @var IL10N */
  12. private $l10n;
  13. /** @var IURLGenerator */
  14. private $urlGenerator;
  15. public function __construct(IL10N $l10n,
  16. IURLGenerator $urlGenerator) {
  17. $this->l10n = $l10n;
  18. $this->urlGenerator = $urlGenerator;
  19. }
  20. public function getId(): string {
  21. return 'mysearchprovider';
  22. }
  23. public function getName(): string {
  24. return $this->l->t('My app');
  25. }
  26. public function getOrder(string $route, array $routeParameters): int {
  27. if (strpos($route, Application::APP_ID . '.') === 0) {
  28. // Active app, prefer my results
  29. return -1;
  30. }
  31. return 25;
  32. }
  33. public function search(IUser $user, ISearchQuery $query): SearchResult {
  34. $offset = ($query->getCursor() ?? 0);
  35. $limit = $query->getLimit();
  36. $data = []; // Fill this with $limit entries, where the first entry is row $offset
  37. return SearchResult::paginated(
  38. $this->l10n->t('My app'),
  39. $data,
  40. $offset + $limit
  41. );
  42. }
  43. }

So the first call will get a cursor of null and a limit of, say, 20. So the first 20 rows are fetched. The next call will have a cursor of 20, so the 20st to 39th rows are fetched.

The downside of a offset-based pagination is that when the underlying data changes (new entries are inserted into or deleted from the database, files change), the offset might be out of sync from on request to its successor. Therefor, if possible, a true cursor-based pagination is preferable.

For a cursor-based pagination a app-specific property is used to know a reference to the last element of the previous search request. The presumption of this algorithm is that the result set is sorted by an attribute and this attribute is an int or string. The attribute value of the last element in the result page determines the cursor for the next search request. Again, a small example shall demonstrate how this works.

  1. <?php
  2. declare(strict_types=1);
  3. namespace OCA\MyApp\Search;
  4. use OCA\MyApp\AppInfo\Application;
  5. use OCP\IL10N;
  6. use OCP\IURLGenerator;
  7. use OCP\IUser;
  8. use OCP\Search\IProvider;
  9. use OCP\Search\SearchResult;
  10. class Provider implements IProvider {
  11. /** @var IL10N */
  12. private $l10n;
  13. /** @var IURLGenerator */
  14. private $urlGenerator;
  15. public function __construct(IL10N $l10n,
  16. IURLGenerator $urlGenerator) {
  17. $this->l10n = $l10n;
  18. $this->urlGenerator = $urlGenerator;
  19. }
  20. public function getId(): string {
  21. return 'mysearchprovider';
  22. }
  23. public function getName(): string {
  24. return $this->l->t('My app');
  25. }
  26. public function getOrder(string $route, array $routeParameters): int {
  27. if (strpos($route, Application::APP_ID . '.') === 0) {
  28. // Active app, prefer my results
  29. return -1;
  30. }
  31. return 25;
  32. }
  33. public function search(IUser $user, ISearchQuery $query): SearchResult {
  34. $cursor = $query->getCursor();
  35. $limit = $query->getLimit();
  36. if ($cursor === null) {
  37. $data = []; // Fill this with $limit entries sorted ascending by created_at
  38. } else {
  39. $data = []; // Fill this with $limit entries sorted ascending by created_at that have a created_at > $cursor
  40. }
  41. $last = end($data);
  42. return SearchResult::paginated(
  43. $this->l10n->t('My app'),
  44. $data,
  45. $last->getCreatedAt()
  46. );
  47. }
  48. }

Optional attributes

The unified search is available via OCS, which means client application like the mobile apps can use it to get access to the server search mechanism. The default properties of a search result entry might be difficult to parse and interpret in those clients, hence it’s possible to add optional string attributes to each entry.

  1. <?php
  2. $entry = new SearchResultEntry(/* same arguments as above */);
  3. $entry->addAttribute("type", "deckCard");
  4. $entry->addAttribute("cardId", "1234");
  5. $entry->addAttribute("boardId", "567");

Note

This method was added in Nextcloud 21. If your app also targets Nextcloud 20 you should either not use it or add a version check to invoke the method only conditionally.