[CALCITE-2347] running ElasticSearch in embedded mode for unit tests of ES adapter...
[calcite.git] / elasticsearch2 / src / main / java / org / apache / calcite / adapter / elasticsearch2 / Elasticsearch2Table.java
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to you under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.calcite.adapter.elasticsearch2;
18
19 import org.apache.calcite.adapter.elasticsearch.AbstractElasticsearchTable;
20 import org.apache.calcite.linq4j.AbstractEnumerable;
21 import org.apache.calcite.linq4j.Enumerable;
22 import org.apache.calcite.linq4j.Enumerator;
23 import org.apache.calcite.linq4j.function.Function1;
24
25 import org.apache.calcite.util.Util;
26
27 import org.elasticsearch.client.Client;
28 import org.elasticsearch.search.SearchHit;
29
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Map;
33
34 /**
35 * Table based on an Elasticsearch2 type.
36 */
37 public class Elasticsearch2Table extends AbstractElasticsearchTable {
38 private final Client client;
39
40 /**
41 * Creates an Elasticsearch2Table.
42 */
43 public Elasticsearch2Table(Client client, String indexName, String typeName) {
44 super(indexName, typeName);
45 this.client = client;
46 }
47
48 /**
49 * ES version 2.x. To access document attributes ES2 uses {@code _source.foo} syntax.
50 */
51 @Override protected String scriptedFieldPrefix() {
52 return "_source";
53 }
54
55 @Override protected Enumerable<Object> find(String index, List<String> ops,
56 List<Map.Entry<String, Class>> fields) {
57 final String dbName = index;
58
59 final String queryString = "{" + Util.toString(ops, "", ", ", "") + "}";
60
61 final Function1<SearchHit, Object> getter = Elasticsearch2Enumerator.getter(fields);
62
63 return new AbstractEnumerable<Object>() {
64 public Enumerator<Object> enumerator() {
65 final Iterator<SearchHit> cursor = client.prepareSearch(dbName).setTypes(typeName)
66 .setSource(queryString).execute().actionGet().getHits().iterator();
67 return new Elasticsearch2Enumerator(cursor, getter);
68 }
69 };
70 }
71 }
72
73 // End Elasticsearch2Table.java