How do I parse json term query using TermQueryBuilder.fromXContent()?

Hi, I'm trying to parse "term query" as JSON string into TermQueryBuilder using TermQueryBuilder.fromXContent();

I looked up Java codes and tried to figure out the way I can parse Json string into TermQueryBuilder.

My intention was I wanted to handle json queries into Java vo objects using Elasticsearch itself which I think it's a sophisticated way.

Is anybody helps me what I've done wroing? it emmitted the exception below.

Thanks in advance.

public class QueryBuilderTest {

    private final List<NamedWriteableRegistry.Entry> namedWriteables = new ArrayList<>();
    private final List<NamedXContentRegistry.Entry> namedXContents = new ArrayList<>();

    @Test
    public void test() throws IOException {
	String term = " {\n" +
	        "    \"term\": {\n" +
	        "      \"poc_category\": {\n" +
	        "        \"value\": \"sample\"\n" +
	        "      }\n" +
	        "    }\n" +
	        "  }";

	System.out.println(term);

	XContentType xContentType = XContentType.JSON;

	registerQuery(new SearchPlugin.QuerySpec<>(TermQueryBuilder.NAME, TermQueryBuilder::new, TermQueryBuilder::fromXContent));

	NamedXContentRegistry registry = new NamedXContentRegistry(namedXContents);
	XContentParser parser = xContentType.xContent().createParser(registry, term);

	QueryParseContext parseContext = new QueryParseContext(parser);

	TermQueryBuilder.fromXContent(parseContext);
    }

    private void registerQuery(SearchPlugin.QuerySpec<?> spec) {
	namedWriteables.add(new NamedWriteableRegistry.Entry(QueryBuilder.class, spec.getName().getPreferredName(), spec.getReader()));
	// Using Optional here is fairly horrible, but in master we don't have to because the builders return QueryBuilder.
	namedXContents.add(new NamedXContentRegistry.Entry(Optional.class, spec.getName(),
	        (XContentParser p, Object c) -> (Optional) spec.getParser().fromXContent((QueryParseContext) c)));
    }
}


java.lang.NullPointerException: fieldName cannot be null

	at java.util.Objects.requireNonNull(Objects.java:228)
	at org.elasticsearch.common.ParseField.match(ParseField.java:108)
	at org.elasticsearch.index.query.QueryParseContext.isDeprecatedSetting(QueryParseContext.java:60)
	at org.elasticsearch.index.query.TermQueryBuilder.fromXContent(TermQueryBuilder.java:98)
	at com.melon.QueryBuilderTest.test(QueryBuilderTest.java:44)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

I think your json should look like this:

String term =  " \"term\": {\n" +
	        "      \"poc_category\": {\n" +
	        "        \"value\": \"sample\"\n" +
	        "      }\n" +
	        "    }";

the outer object is the responsibility of the caller.

Thx for the fast reply.
I tried to change term variable, but my console still emitts the same error message.

@Test
public void test() throws IOException {
    String term =  " \"term\": {\n" +
            "      \"poc_category\": {\n" +
            "        \"value\": \"sample\"\n" +
            "      }\n" +
            "    }";

    System.out.println(term);

    XContentType xContentType = XContentType.JSON;

    registerQuery(new SearchPlugin.QuerySpec<>(TermQueryBuilder.NAME, TermQueryBuilder::new, TermQueryBuilder::fromXContent));

    NamedXContentRegistry registry = new NamedXContentRegistry(namedXContents);
    XContentParser parser = xContentType.xContent().createParser(registry, term);

    QueryParseContext parseContext = new QueryParseContext(parser);

    TermQueryBuilder.fromXContent(parseContext);
}

console

java.lang.NullPointerException: fieldName cannot be null

	at java.util.Objects.requireNonNull(Objects.java:228)
	at org.elasticsearch.common.ParseField.match(ParseField.java:108)
	at org.elasticsearch.index.query.QueryParseContext.isDeprecatedSetting(QueryParseContext.java:60)
	at org.elasticsearch.index.query.TermQueryBuilder.fromXContent(TermQueryBuilder.java:98)
	at com.melon.QueryBuilderTest.test(QueryBuilderTest.java:44)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

I took a closer look and this works for me:

   String term =  " {\"term\": {\n" +
        "      \"poc_category\": {\n" +
        "        \"value\": \"sample\"\n" +
        "      }\n" +
        "    }}";


    XContentParser parser = createParser(JsonXContent.jsonXContent, term);
    AbstractQueryBuilder.parseInnerQueryBuilder(parser);

Thanks a lot.

I ran it successfully the code below because I'm supposed to use this on my production code.

package org;

import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.plugins.SearchPlugin;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class UnitTest {

    private final List<NamedWriteableRegistry.Entry> namedWriteables = new ArrayList<>();
    private final List<NamedXContentRegistry.Entry> namedXContents = new ArrayList<>();

    @Test
    public void test2() throws IOException {
	String term =  " {\"term\": {\n" +
	    "      \"poc_category\": {\n" +
	    "        \"value\": \"sample\"\n" +
	    "      }\n" +
	    "    }}";

	registerQuery(new SearchPlugin.QuerySpec<>(TermQueryBuilder.NAME, TermQueryBuilder::new, TermQueryBuilder::fromXContent));
//
	NamedXContentRegistry registry = new NamedXContentRegistry(namedXContents);
	XContentParser parser = JsonXContent.jsonXContent.createParser(registry, term);
	QueryBuilder qb = AbstractQueryBuilder.parseInnerQueryBuilder(parser);
	System.out.println("qb = " + qb.toString());

    }

    private void registerQuery(SearchPlugin.QuerySpec<?> spec) {
	namedWriteables.add(new NamedWriteableRegistry.Entry(QueryBuilder.class, spec.getName().getPreferredName(), spec.getReader()));
	namedXContents.add(new NamedXContentRegistry.Entry(QueryBuilder.class, spec.getName(),
	    (p, c) -> spec.getParser().fromXContent(p)));
    }
}

I also refactored the code which I think I don't need to use ES 6.x.

@Test
public void term() throws IOException {
    String term = "  {\n" +
        "      \"poc_category\": {\n" +
        "        \"value\": \"sample\"\n" +
        "      }\n" +
        "    }";

    NamedXContentRegistry registry = new NamedXContentRegistry(ClusterModule.getNamedXWriteables());
    XContentParser parser = JsonXContent.jsonXContent.createParser(registry, term);
    parser.nextToken();

    TermQueryBuilder qb = TermQueryBuilder.fromXContent(parser);
    System.out.println("qb = " + qb.toString());
}

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.