ElasticGraph Query API: Highlighting

Try these example queries by visiting the GraphiQL UI after booting locally.

When searching through textual data it can be very useful to know where matches occurred in the returned documents. For example, to power a “global search” box that lets users search across all string/text fields, you could use a query like this:

query GlobalSearch(
  $query: String = "Rock" # an example search term; replace with whatever you want
) {
  artists(filter: {
    anyOf: [
      {albums: {anySatisfy: {name: {contains: {anySubstringOf: [$query]}}}}}
      {albums: {anySatisfy: {tracks: {anySatisfy: {name: {contains: {anySubstringOf: [$query]}}}}}}}
      {bio: {homeCountry: {equalToAnyOf: [$query]}}}
      {bio: {description: {matchesQuery: {query: $query}}}}
      {name: {contains: {anySubstringOf: [$query]}}}
      {tours: {anySatisfy: {name: {contains: {anySubstringOf: [$query]}}}}}
    ]
  }) {
    edges {
      node {
        name
      }

      highlights {
        albums {
          name
          tracks {
            name
          }
        }

        bio {
          homeCountry
          description
        }

        name

        tours {
          name
        }
      }
    }
  }
}

The returned highlights will contain snippets from the matching fields to show why a particular search result was returned.

Simpler Highlighting With allHighlights

ElasticGraph also offers allHighlights as an alternative to highlights which allows the query to be simplified a bit:

query GlobalSearchV2(
  $query: String = "Rock" # an example search term; replace with whatever you want
) {
  artists(filter: {
    anyOf: [
      {albums: {anySatisfy: {name: {contains: {anySubstringOf: [$query]}}}}}
      {albums: {anySatisfy: {tracks: {anySatisfy: {name: {contains: {anySubstringOf: [$query]}}}}}}}
      {bio: {homeCountry: {equalToAnyOf: [$query]}}}
      {bio: {description: {matchesQuery: {query: $query}}}}
      {name: {contains: {anySubstringOf: [$query]}}}
      {tours: {anySatisfy: {name: {contains: {anySubstringOf: [$query]}}}}}
    ]
  }) {
    edges {
      node {
        name
      }

      allHighlights {
        path
        snippets
      }
    }
  }
}

Rather than providing the nested structure with named fields provided by highlights, this provides the highlights as a flat list of SearchHighlight objects, each of which has a path indicating the matching field.

Note While clients usually have the option to use edges or nodes, highlights and allHighlights are only available from edges.