Skip to content

Instantly share code, notes, and snippets.

@ellerycrane
Created May 16, 2011 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ellerycrane/974865 to your computer and use it in GitHub Desktop.
Save ellerycrane/974865 to your computer and use it in GitHub Desktop.
elasticsearch java api should clause spec
import org.elasticsearch.common.xcontent.ToXContent
import org.elasticsearch.common.xcontent.XContentBuilder
import org.elasticsearch.common.xcontent.XContentFactory
import org.elasticsearch.index.query.QueryBuilder
import org.elasticsearch.index.query.xcontent.QueryStringQueryBuilder
import spock.lang.Specification
import static org.elasticsearch.index.query.xcontent.QueryBuilders.boolQuery
import static org.elasticsearch.index.query.xcontent.QueryBuilders.queryString
class ShouldClauseSpec extends Specification{
def "should clauses to bool queries should get aggregated appropriately"(){
setup:
QueryStringQueryBuilder clauseOne = (QueryStringQueryBuilder) (queryString("charles").useDisMax(true))
clauseOne.field('user.name.first')
clauseOne.field('user.email')
//incidentally, it would be nice to have a 'fields' method that takes a collection of strings instead of doing it this way
QueryStringQueryBuilder clauseTwo = (QueryStringQueryBuilder) (queryString("xavier").useDisMax(true))
clauseOne.field('user.name.last')
clauseOne.field('user.email')
QueryBuilder query = boolQuery()
when:
query.should(clauseOne)
query.should(clauseTwo)
String json = getJson(query)
/* this is what we get:
{
"bool": {
"should": {
"query_string": {
"query": "charles",
"fields": ["user.name.first", "user.email", "user.name.last", "user.email"],
"use_dis_max": true
}
},
"should": {
"query_string": {
"query": "xavier",
"use_dis_max": true
}
}
}
}
*/
then:
json.count('should') == 1 //we should have only one should clause
json.count('query_string') == 2 //we should have two query string queries
json.count('fields') == 2 //we should have two different fields properties
json.contains('["user.name.first", "user.email"]') //the first fields array
json.contains('["user.name.last", "user.email"]') //the second fields array
}
private String getJson(builder){
XContentBuilder jsonBuilder = XContentFactory.jsonBuilder()
XContentBuilder toXContent = builder.toXContent(jsonBuilder, ToXContent.EMPTY_PARAMS)
return toXContent.string()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment