Search code examples
javaelasticsearchelasticsearch-plugin

Elasticsearch query plugin


I'm upgrading an Elasticsearch plugin from version 2.4.0 to 5.4.0. This plugin implements a custom query but with the new changes on Elasticsearch Java Api I'm a little confused in how to register the new query. I search in Elasticsearch site and I found that I must implement the SearchPlugin interfaces and override the method getQueriesbut I'm still confuse and how I do that. Any help?


Solution

  • You need something like this (java8):

    public class MyQueryPlugin extends Plugin implements SearchPlugin {
    
        @Override public List<QuerySpec<?>> getQueries() {
            return Arrays.asList(
                    new QuerySpec<>("my_query", MyQueryBuilder::new, MyQueryBuilder::fromXContent)
            );
        }
    }
    

    Or this (java 7):

    public class MyQueryPlugin extends Plugin implements SearchPlugin {
    
        @Override
        public List<QuerySpec<?>> getQueries() {
            return Arrays.asList(new QuerySpec<>(
                    "my_query",
                    new Writeable.Reader<MyQueryBuilder>() {
                        @Override
                        public MyQueryBuilder read(StreamInput in) throws IOException {return new MyQueryBuilder(in);}
                    },
                    new QueryParser<MyQueryBuilder>() {
                        @Override
                        public Optional<MyQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException {return MyQueryBuilder.fromXContent(parseContext);}
                    })
            );
        }
    }
    

    MyQueryBuilder will probably extend AbstractQueryBuilder<MyQueryBuilder>. Most other ES-provided queries extend this - they're a good source to copy from.

    MyQueryBuilder::fromXContent is the other change that caught me out - it should do the same as org.elasticsearch.index.query.QueryParser#parse(QueryParseContext parseContext) from 2.x.

    MyQueryPlugin is what you'd reference in your plugin-descriptor.properties like:

    description=my-query example
    version=1.0.0
    name=my-query
    java.version=1.8
    elasticsearch.version=5.4.0
    classname=com.example.MyQueryPlugin