Skip to content

Commit

Permalink
HSEARCH-2441 Only accept the 'query' root attribute in ElasticsearchQ…
Browse files Browse the repository at this point in the history
…uerys.fromJson
  • Loading branch information
yrodiere authored and Sanne committed Dec 19, 2016
1 parent e9e27e5 commit 3066616
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
Expand Up @@ -6,10 +6,20 @@
*/
package org.hibernate.search.elasticsearch;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.search.elasticsearch.impl.ElasticsearchJsonQueryDescriptor;
import org.hibernate.search.elasticsearch.impl.JsonBuilder;
import org.hibernate.search.elasticsearch.logging.impl.Log;
import org.hibernate.search.query.engine.spi.QueryDescriptor;
import org.hibernate.search.util.impl.CollectionHelper;
import org.hibernate.search.util.logging.impl.LoggerFactory;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
Expand All @@ -22,18 +32,38 @@
*/
public class ElasticsearchQueries {

private static final Log LOG = LoggerFactory.make( Log.class );

private static final JsonParser PARSER = new JsonParser();

private static final Set<String> ALLOWED_PAYLOAD_ATTRIBUTES = Collections.unmodifiableSet(
CollectionHelper.asSet( "query" ) );

private ElasticsearchQueries() {
}

/**
* Creates an Elasticsearch query from the given JSON payload for the Elasticsearch Search API.
* <p>
* Note that only the 'query' attribute is supported.
* <p>
* See the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html">
* official documentation</a> for the complete payload syntax.
*/
public static QueryDescriptor fromJson(String payload) {
JsonObject payloadAsJsonObject = PARSER.parse( payload ).getAsJsonObject();

List<String> invalidAttributes = new ArrayList<>();
for ( Map.Entry<String, ?> entry : payloadAsJsonObject.entrySet() ) {
String payloadAttribute = entry.getKey();
if ( ! ALLOWED_PAYLOAD_ATTRIBUTES.contains( payloadAttribute ) ) {
invalidAttributes.add( payloadAttribute );
}
}
if ( !invalidAttributes.isEmpty() ) {
throw LOG.unsupportedSearchAPIPayloadAttributes( invalidAttributes );
}

return new ElasticsearchJsonQueryDescriptor( PARSER.parse( payload ).getAsJsonObject() );
}

Expand Down
Expand Up @@ -283,4 +283,8 @@ BulkRequestFailedException elasticsearchBulkRequestFailed(String request, String
value = "The index '%1$s' does not exist in the Elasticsearch cluster." )
SearchException indexMissing(String indexName);

@Message(id = ES_BACKEND_MESSAGES_START_ID + 51,
value = "The given payload contains unsupported attributes: %1$s. Only 'query' is supported." )
SearchException unsupportedSearchAPIPayloadAttributes(List<String> invalidAttributes);

}

0 comments on commit 3066616

Please sign in to comment.