Merge pull request #16068 from jasontedor/ip-field-mapper-term-queries

Single IPv4 addresses in IP field term queries

Closes #16058
This commit is contained in:
Jason Tedor 2016-01-18 17:46:50 -05:00
commit b6c9eaa24a
2 changed files with 27 additions and 3 deletions

View File

@ -213,11 +213,24 @@ public class IpFieldMapper extends NumberFieldMapper {
@Override
public Query termQuery(Object value, @Nullable QueryShardContext context) {
if (value != null) {
long[] fromTo;
String term;
if (value instanceof BytesRef) {
fromTo = Cidrs.cidrMaskToMinMax(((BytesRef) value).utf8ToString());
term = ((BytesRef) value).utf8ToString();
} else {
fromTo = Cidrs.cidrMaskToMinMax(value.toString());
term = value.toString();
}
long[] fromTo;
// assume that the term is either a CIDR range or the
// term is a single IPv4 address; if either of these
// assumptions is wrong, the CIDR parsing will fail
// anyway, and that is okay
if (term.contains("/")) {
// treat the term as if it is in CIDR notation
fromTo = Cidrs.cidrMaskToMinMax(term);
} else {
// treat the term as if it is a single IPv4, and
// apply a CIDR mask equivalent to the host route
fromTo = Cidrs.cidrMaskToMinMax(term + "/32");
}
if (fromTo != null) {
return rangeQuery(fromTo[0] == 0 ? null : fromTo[0],

View File

@ -40,6 +40,7 @@ import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFailures;
@ -124,6 +125,16 @@ public class SimpleSearchIT extends ESIntegTestCase {
refresh();
SearchResponse search = client().prepareSearch()
.setQuery(boolQuery().must(QueryBuilders.termQuery("ip", "192.168.0.1")))
.execute().actionGet();
assertHitCount(search, 1L);
search = client().prepareSearch()
.setQuery(queryStringQuery("ip: 192.168.0.1"))
.execute().actionGet();
assertHitCount(search, 1L);
search = client().prepareSearch()
.setQuery(boolQuery().must(QueryBuilders.termQuery("ip", "192.168.0.1/32")))
.execute().actionGet();
assertHitCount(search, 1l);