Skip to content

Commit

Permalink
Make ip field parsing easier to read (elastic#76363)
Browse files Browse the repository at this point in the history
This makes the IP parsing code in `IpFieldMapper` a little easier to
read by removing the string/object juggling. It also pulls the value
parsing bit out into a very sensible and readable method. As a bonus,
this method is reusable and we *do* plan to reuse it.
  • Loading branch information
nik9000 committed Aug 11, 2021
1 parent a48c736 commit 72ba4cd
Showing 1 changed file with 19 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.elasticsearch.common.logging.DeprecationCategory;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.network.InetAddresses;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.Tuple;
import org.elasticsearch.index.fielddata.IndexFieldData;
Expand Down Expand Up @@ -443,34 +444,28 @@ protected String contentType() {

@Override
protected void parseCreateField(DocumentParserContext context) throws IOException {
Object addressAsObject = context.parser().textOrNull();

if (addressAsObject == null) {
addressAsObject = nullValue;
}

if (addressAsObject == null) {
return;
}

String addressAsString = addressAsObject.toString();
InetAddress address;
if (addressAsObject instanceof InetAddress) {
address = (InetAddress) addressAsObject;
} else {
try {
address = InetAddresses.forString(addressAsString);
} catch (IllegalArgumentException e) {
if (ignoreMalformed) {
context.addIgnoredField(fieldType().name());
return;
} else {
throw e;
}
try {
address = value(context.parser(), nullValue);
} catch (IllegalArgumentException e) {
if (ignoreMalformed) {
context.addIgnoredField(fieldType().name());
return;
} else {
throw e;
}
}
if (address != null) {
indexValue(context, address);
}
}

indexValue(context, address);
private static InetAddress value(XContentParser parser, InetAddress nullValue) throws IOException {
String value = parser.textOrNull();
if (value == null) {
return nullValue;
}
return InetAddresses.forString(value);
}

private void indexValue(DocumentParserContext context, InetAddress address) {
Expand Down Expand Up @@ -507,5 +502,4 @@ protected void indexScriptValues(SearchLookup searchLookup, LeafReaderContext re
public FieldMapper.Builder getMergeBuilder() {
return new Builder(simpleName(), scriptCompiler, ignoreMalformedByDefault, indexCreatedVersion).dimension(dimension).init(this);
}

}

0 comments on commit 72ba4cd

Please sign in to comment.