About Search query (HS 6 Beta 11)

want to use two queries like below

  1. terms
{
  "query": {
    "terms": {
      "user.id": [ "kimchy", "elkbee" ]
    }
  }
}

or

{
  "query": {
    "terms": {
      "user.age": [ 20, 30 ]
    }
  }
}
  1. query - bool - filter
{
  "query": {
    "bool": {
    	"filter": [{
          "terms": {
            "id": [1, 2]
          }
        }]
    }
  }
}

I could’t find usage in the documentation (https://docs.jboss.org/hibernate/search/6.0/reference/en-US/html_single/)

please let me know usage.

The terms predicate is not yet available in the Hibernate Search DSL.

For non-analyzed text fields or numeric fields, the match predicate will behave similarly to the terms predicate. It does not allow passing multiple values to match (yet), but you can do it yourself with a boolean predicate:

List<String> ids = new ArrayList<>();
ids.add( "kimchy" );
ids.add( "elkbee" );
List<Book> hits = searchSession.search( Book.class )
        .where( f -> f.bool( b -> {
            for ( String id : ids ) {
                b.should( f.match().field( "user.id" ).matching( id ) );
            }
        } )
        .fetchHits( 20 );

To match on the document ID (which I assume has the same value as your id field), I would recommend the id predicate, which (on the contrary to match) offers a matchingAny method accepting multiple values to match:

List<Integer> ids = new ArrayList<>();
ids.add( 1 );
ids.add( 2 );
List<Book> hits = searchSession.search( Book.class )
        .where( f -> f.id().matchingAny( ids ) )
        .fetchHits( 20 );

Finally, if you really need particular JSON and can’t find what you want in the Hibernate Search DSL, you can embed your JSON in the Hibernate Search query.

1 Like

To anyone reading this thread, the terms predicate will be coming to Hibernate Search 6.1: https://hibernate.atlassian.net/browse/HSEARCH-2589

1 Like

The terms predicate is there:

So you can create this query:

{
  "query": {
    "terms": {
      "user.id": [ "kimchy", "elkbee" ]
    }
  }
}

Like this:

List<Book> hits = searchSession.search( Book.class )
        .where( f -> f.terms().field( "user.id" )
                        .matchingAny( "kimchy", "elkbee" ) )
        .fetchHits( 20 );

Be aware that the terms predicate does not perform analysis (tokenization, normalization, etc.), so it’s mostly useful for ID fields, or enum fields, etc. Not for full-text search.

See also:

https://docs.jboss.org/hibernate/search/6.1/reference/en-US/html_single/#search-dsl-predicate-terms