Skip to content

Commit f5070c7

Browse files
committed
Add test files to be included as doc snippets
1 parent fe8d8da commit f5070c7

File tree

4 files changed

+473
-0
lines changed

4 files changed

+473
-0
lines changed
Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
/*
2+
* Licensed to Elasticsearch B.V. under one or more contributor
3+
* license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright
5+
* ownership. Elasticsearch B.V. licenses this file to you under
6+
* the Apache License, Version 2.0 (the "License"); you may
7+
* not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
20+
package co.elastic.clients.documentation;
21+
22+
import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
23+
import co.elastic.clients.elasticsearch.ElasticsearchClient;
24+
import co.elastic.clients.elasticsearch._types.SortOrder;
25+
import co.elastic.clients.elasticsearch._types.aggregations.Aggregation;
26+
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
27+
import co.elastic.clients.elasticsearch.core.SearchRequest;
28+
import co.elastic.clients.elasticsearch.core.SearchResponse;
29+
import co.elastic.clients.elasticsearch.indices.Alias;
30+
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
31+
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
32+
import co.elastic.clients.transport.ElasticsearchTransport;
33+
import co.elastic.clients.transport.TransportException;
34+
import org.junit.Assert;
35+
import org.junit.Test;
36+
37+
import java.util.Arrays;
38+
import java.util.HashMap;
39+
import java.util.List;
40+
import java.util.Map;
41+
import java.util.logging.LogManager;
42+
import java.util.logging.Logger;
43+
44+
public class ApiConventionsTest extends Assert {
45+
46+
private static class SomeApplicationData {}
47+
48+
private ElasticsearchTransport transport = new FailingTransport();
49+
Logger logger = LogManager.getLogManager().getLogger(ApiConventionsTest.class.getName());
50+
51+
@Test(expected = TransportException.class)
52+
public void blockingAndAsync() throws Exception {
53+
54+
//tag::blocking-and-async
55+
// Synchronous blocking client
56+
ElasticsearchClient client = new ElasticsearchClient(transport);
57+
58+
if (client.exists(b -> b.index("products").id("foo")).value()) {
59+
logger.info("product exists");
60+
}
61+
62+
// Asynchronous non-blocking client
63+
ElasticsearchAsyncClient asyncClient =
64+
new ElasticsearchAsyncClient(transport);
65+
66+
asyncClient
67+
.exists(b -> b.index("products").id("foo"))
68+
.thenAccept(response -> {
69+
if (response.value()) {
70+
logger.info("product exists");
71+
}
72+
});
73+
//end::blocking-and-async
74+
75+
}
76+
77+
@Test(expected = TransportException.class)
78+
public void builders() throws Exception {
79+
ElasticsearchClient client = new ElasticsearchClient(transport);
80+
81+
//tag::builders
82+
CreateIndexResponse createResponse = client.indices().create(
83+
new CreateIndexRequest.Builder()
84+
.index("my-index")
85+
.aliases("foo",
86+
new Alias.Builder().isWriteIndex(true).build()
87+
)
88+
.build()
89+
);
90+
//end::builders
91+
}
92+
93+
@Test(expected = TransportException.class)
94+
public void builderLambdas() throws Exception {
95+
ElasticsearchClient client = new ElasticsearchClient(transport);
96+
97+
//tag::builder-lambdas
98+
CreateIndexResponse createResponse = client.indices()
99+
.create(createIndexBuilder -> createIndexBuilder
100+
.index("my-index")
101+
.aliases("foo", aliasBuilder -> aliasBuilder
102+
.isWriteIndex(true)
103+
)
104+
);
105+
//end::builder-lambdas
106+
}
107+
108+
@Test(expected = TransportException.class)
109+
public void builderLambdasShort() throws Exception {
110+
ElasticsearchClient client = new ElasticsearchClient(transport);
111+
112+
//tag::builder-lambdas-short
113+
CreateIndexResponse createResponse = client.indices()
114+
.create(c -> c
115+
.index("my-index")
116+
.aliases("foo", a -> a
117+
.isWriteIndex(true)
118+
)
119+
);
120+
//end::builder-lambdas-short
121+
}
122+
123+
@Test(expected = TransportException.class)
124+
public void builderIntervals() throws Exception {
125+
ElasticsearchClient client = new ElasticsearchClient(transport);
126+
127+
//tag::builder-intervals
128+
SearchResponse<SomeApplicationData> results = client
129+
.search(_0 -> _0
130+
.query(_1 -> _1
131+
.intervals(_2 -> _2
132+
.field("my_text")
133+
.allOf(_3 -> _3
134+
.ordered(true)
135+
.intervals(_4 -> _4
136+
.match(_5 -> _5
137+
.query("my favorite food")
138+
.maxGaps(0)
139+
.ordered(true)
140+
)
141+
)
142+
.intervals(_4 -> _4
143+
.anyOf(_5 -> _5
144+
.intervals(_6 -> _6
145+
.match(_7 -> _7
146+
.query("hot water")
147+
)
148+
)
149+
.intervals(_6 -> _6
150+
.match(_7 -> _7
151+
.query("cold porridge")
152+
)
153+
)
154+
)
155+
)
156+
)
157+
)
158+
),
159+
SomeApplicationData.class // <1>
160+
);
161+
//end::builder-intervals
162+
}
163+
164+
@Test
165+
public void variantCreation() {
166+
//tag::variant-creation
167+
Query query = new Query.Builder()
168+
.term(t -> t // <1>
169+
.field("name") // <2>
170+
.value(v -> v.stringValue("foo"))
171+
)
172+
.build(); // <3>
173+
//end::variant-creation
174+
175+
//tag::variant-navigation
176+
assertEquals("foo", query.term().value().stringValue());
177+
//end::variant-navigation
178+
179+
//tag::variant-kind
180+
if (query.isTerm()) { // <1>
181+
doSomething(query.term());
182+
}
183+
184+
switch(query._kind()) { // <2>
185+
case Term:
186+
doSomething(query.term());
187+
break;
188+
case Intervals:
189+
doSomething(query.intervals());
190+
break;
191+
default:
192+
doSomething(query._kind(), query._get()); // <3>
193+
}
194+
//end::variant-kind
195+
}
196+
197+
@Test
198+
public void collections() {
199+
//tag::collections-list
200+
// Prepare a list of index names
201+
List<String> names = Arrays.asList("idx-a", "idx-b", "idx-c");
202+
203+
// Prepare cardinality aggregations for fields "foo" and "bar"
204+
Map<String, Aggregation> cardinalities = new HashMap<>();
205+
cardinalities.put("foo-count", Aggregation.of(a -> a.cardinality(c -> c.field("foo"))));
206+
cardinalities.put("bar-count", Aggregation.of(a -> a.cardinality(c -> c.field("bar"))));
207+
208+
// Prepare an aggregation that computes the average of the "size" field
209+
final Aggregation avgSize = Aggregation.of(a -> a.avg(v -> v.field("size")));
210+
211+
SearchRequest search = SearchRequest.of(r -> r
212+
// Index list:
213+
// - add all elements of a list
214+
.index(names)
215+
// - add a single element
216+
.index("idx-d")
217+
// - add a vararg list of elements
218+
.index("idx-e", "idx-f", "idx-g")
219+
220+
// Sort order list: add elements defined by builder lambdas
221+
.sort(s -> s.field(f -> f.field("foo").order(SortOrder.Asc)))
222+
.sort(s -> s.field(f -> f.field("bar").order(SortOrder.Desc)))
223+
224+
// Aggregation map:
225+
// - add all entries of an existing map
226+
.aggregations(cardinalities)
227+
// - add a key/value entry
228+
.aggregations("avg-size", avgSize)
229+
// - add a key/value defined by a builder lambda
230+
.aggregations("price-histogram",
231+
a -> a.histogram(h -> h.field("price")))
232+
);
233+
//end::collections-list
234+
235+
}
236+
237+
private void doSomething(Object... o) {
238+
239+
}
240+
}
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/*
2+
* Licensed to Elasticsearch B.V. under one or more contributor
3+
* license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright
5+
* ownership. Elasticsearch B.V. licenses this file to you under
6+
* the Apache License, Version 2.0 (the "License"); you may
7+
* not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
20+
package co.elastic.clients.documentation;
21+
22+
import co.elastic.clients.elasticsearch.ElasticsearchClient;
23+
import co.elastic.clients.elasticsearch.core.SearchResponse;
24+
import co.elastic.clients.elasticsearch.core.search.Hit;
25+
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
26+
import co.elastic.clients.transport.ElasticsearchTransport;
27+
import co.elastic.clients.transport.rest_client.RestClientTransport;
28+
import org.apache.http.HttpHost;
29+
import org.elasticsearch.client.RestClient;
30+
import org.junit.Ignore;
31+
import org.junit.Test;
32+
33+
public class ConnectingTest {
34+
35+
private static class Product{}
36+
37+
@Ignore // we don't have a running ES
38+
@Test
39+
public void createClient() throws Exception {
40+
//tag::create-client
41+
// Create the low-level client
42+
RestClient restClient = RestClient.builder(
43+
new HttpHost("localhost", 9200)).build();
44+
45+
// Create the transport with a Jackson mapper
46+
ElasticsearchTransport transport = new RestClientTransport(
47+
restClient, new JacksonJsonpMapper());
48+
49+
// And create the API client
50+
ElasticsearchClient client = new ElasticsearchClient(transport);
51+
//end::create-client
52+
53+
//tag::first-request
54+
SearchResponse<Product> search = client.search(s -> s
55+
.index("products")
56+
.query(q -> q
57+
.term(t -> t
58+
.field("name")
59+
.value(v -> v.stringValue("bicycle"))
60+
)),
61+
Product.class);
62+
63+
for (Hit<Product> hit: search.hits().hits()) {
64+
processProduct(hit.source());
65+
}
66+
//end::first-request
67+
}
68+
69+
private void processProduct(Product p) {}
70+
71+
}

0 commit comments

Comments
 (0)