Anda dapat menggunakan SDK untuk mengkueri data di bidang tipe nested tingkat tunggal maupun multi-level. Saat melakukan kueri bersarang, Anda dapat menggunakan fitur highlight untuk menyoroti kata kunci dalam hasil. Untuk informasi selengkapnya tentang penyorotan, lihat highlight.
Contoh kueri nested tingkat tunggal
Contoh berikut menunjukkan cara mengkueri data di mana `col_nested.nested_1` adalah `tablestore`. Dalam contoh ini, `col_nested` adalah bidang nested yang baris anaknya berisi kolom `nested_1` dan `nested_2`.
private static void nestedQuery(SyncClient client) {
SearchQuery searchQuery = new SearchQuery();
NestedQuery nestedQuery = new NestedQuery(); // Set the query type to NestedQuery.
nestedQuery.setPath("col_nested"); // Set the path of the nested column.
TermQuery termQuery = new TermQuery(); // Construct the subquery for NestedQuery.
termQuery.setFieldName("col_nested.nested_1"); // Set the column name. Note that it includes the path of the nested column.
termQuery.setTerm(ColumnValue.fromString("tablestore")); // Set the value to query.
nestedQuery.setQuery(termQuery);
nestedQuery.setScoreMode(ScoreMode.None);
searchQuery.setQuery(nestedQuery);
//searchQuery.setGetTotalCount(true); // Set this to return the total number of matched rows.
SearchRequest searchRequest = new SearchRequest("<TABLE_NAME>", "<SEARCH_INDEX_NAME>", searchQuery);
// Use the columnsToGet parameter to specify the columns to return or to return all columns. If you do not set this parameter, only the primary key columns are returned by default.
//SearchRequest.ColumnsToGet columnsToGet = new SearchRequest.ColumnsToGet();
//columnsToGet.setReturnAll(true); // Set this to return all columns.
//columnsToGet.setColumns(Arrays.asList("ColName1","ColName2")); // Set this to return specified columns.
//searchRequest.setColumnsToGet(columnsToGet);
SearchResponse resp = client.search(searchRequest);
//System.out.println("TotalCount: " + resp.getTotalCount()); // Print the total number of matched rows, not the number of returned rows.
System.out.println("Row: " + resp.getRows());
}
Contoh kueri nested multi-level
Contoh berikut menunjukkan cara mengkueri data di mana `col_nested.nested_2.nested_2_2` adalah `tablestore`. Dalam contoh ini, `col_nested` adalah bidang nested yang baris anaknya berisi kolom `nested_1` dan `nested_2`. Kolom `nested_2` juga merupakan bidang nested yang baris anaknya berisi kolom `nested_2_1` dan `nested_2_2`.
private static void nestedQuery(SyncClient client) {
SearchQuery searchQuery = new SearchQuery();
NestedQuery nestedQuery = new NestedQuery(); // Set the query type to NestedQuery.
nestedQuery.setPath("col_nested.nested_2"); // Set the path of the nested column, which is the parent path of the field to query.
TermQuery termQuery = new TermQuery(); // Construct the subquery for NestedQuery.
termQuery.setFieldName("col_nested.nested_2.nested_2_2"); // Set the column name, which is the full path of the field to query.
termQuery.setTerm(ColumnValue.fromString("tablestore")); // Set the value to query.
nestedQuery.setQuery(termQuery);
nestedQuery.setScoreMode(ScoreMode.None);
searchQuery.setQuery(nestedQuery);
//searchQuery.setGetTotalCount(true); // Set this to return the total number of matched rows.
SearchRequest searchRequest = new SearchRequest("<TABLE_NAME>", "<SEARCH_INDEX_NAME>", searchQuery);
// Use the columnsToGet parameter to specify the columns to return or to return all columns. If you do not set this parameter, only the primary key columns are returned by default.
//SearchRequest.ColumnsToGet columnsToGet = new SearchRequest.ColumnsToGet();
//columnsToGet.setReturnAll(true); // Set this to return all columns.
//columnsToGet.setColumns(Arrays.asList("ColName1","ColName2")); // Set this to return specified columns.
//searchRequest.setColumnsToGet(columnsToGet);
SearchResponse resp = client.search(searchRequest);
//System.out.println("TotalCount: " + resp.getTotalCount()); // Print the total number of matched rows, not the number of returned rows.
System.out.println("Row: " + resp.getRows());
}
Contoh kueri nested komposit
Kebutuhan kueri
Asumsikan bahwa sebuah tabel data memiliki dua kolom: `col_string` (String) dan `col_nested` (String). Kolom `col_nested` menyimpan data dalam format JSON. Tabel berikut menunjukkan data sampel dari tabel data ini.
Catatan
Kolom nomor baris ditambahkan ke setiap baris untuk tujuan demonstrasi.
|
Nomor baris
|
col_string
|
col_nested
|
|
1
|
a
|
[{"col_keyword": "tablestore"},{"col_keyword": "searchindex","col_long": 1}]
|
|
2
|
b
|
[{"col_keyword": "tablestore","col_long": 1}]
|
|
3
|
c
|
[{"col_keyword": "searchindex"},{"col_long": 1}]
|
Asumsikan bahwa Anda memiliki kebutuhan kueri berikut untuk data dalam kolom `col_nested`:
-
Satu baris anak memenuhi beberapa kondisi kueri
Misalnya, Anda dapat mengkueri baris di mana satu baris anak dalam kolom `col_nested` memenuhi kedua kondisi berikut: nilai kolom `col_keyword` adalah `tablestore` dan nilai kolom `col_long` tidak kosong.
-
Baris anak berbeda memenuhi beberapa kondisi kueri
Misalnya, Anda dapat mengkueri baris di mana satu baris anak dalam kolom `col_nested` memiliki nilai `col_keyword` sebesar `tablestore`, dan baris anak lain memiliki nilai `col_long` yang tidak kosong.
Untuk memenuhi kebutuhan kueri ini, Anda dapat melakukan langkah-langkah berikut:
-
Buat indeks pencarian untuk tabel data dan atur kolom `col_nested` sebagai tipe nested dalam indeks pencarian.
Kolom `col_nested` berisi dua sub-field: `col_keyword` (Keyword) dan `col_long` (Long).
-
Gunakan metode kueri yang sesuai berdasarkan kebutuhan Anda.
-
Untuk melakukan kueri di mana satu baris anak memenuhi beberapa kondisi kueri, konfigurasikan beberapa BoolQueries di dalam NestedQuery.
-
Untuk mengkueri baris anak berbeda yang memenuhi beberapa kondisi, Anda dapat mengatur beberapa kondisi `NestedQuery` di bawah `BoolQuery`.
Contoh berikut menunjukkan cara mengkueri data. Anda dapat merujuk pada contoh yang sesuai dengan kebutuhan kueri Anda.
Contoh kueri di mana satu baris anak memenuhi beberapa kondisi
Contoh berikut menunjukkan cara mengkueri baris di mana satu baris anak dalam kolom `col_nested` memenuhi kedua kondisi ini: `col_nested.col_keyword adalah "tablestore" dan `col_nested.col_long tidak kosong.
Berdasarkan data sampel, hanya data di baris 2 yang memenuhi kondisi kueri.
public static void nestedQuery(SyncClient client) {
// Condition 1: The value of the col_keyword column in the child row of col_nested must be "tablestore".
TermQuery termQuery = new TermQuery();
termQuery.setFieldName("col_nested.col_keyword");
termQuery.setTerm(ColumnValue.fromString("tablestore"));
// Condition 2: The col_long column in the child row of col_nested must not be empty.
ExistsQuery existsQuery = new ExistsQuery();
existsQuery.setFieldName("col_nested.col_long");
// Use the AND condition of BoolQuery to query for child rows that meet both conditions.
List<Query> mustQueries = new ArrayList<>();
mustQueries.add(termQuery);
mustQueries.add(existsQuery);
BoolQuery boolQuery = new BoolQuery();
boolQuery.setMustQueries(mustQueries);
// Set a BoolQuery within the NestedQuery to require a child row to meet multiple query conditions at the same time.
NestedQuery nestedQuery = new NestedQuery(); // Set the query type to NestedQuery.
nestedQuery.setPath("col_nested"); // Set the path of the nested column, which is the parent path of the field to query.
nestedQuery.setQuery(boolQuery);
nestedQuery.setScoreMode(ScoreMode.None);
SearchQuery searchQuery = new SearchQuery();
searchQuery.setQuery(nestedQuery);
SearchRequest searchRequest = new SearchRequest("<TABLE_NAME>", "<SEARCH_INDEX_NAME>", searchQuery);
// Use the columnsToGet parameter to specify the columns to return or to return all columns. If you do not set this parameter, only the primary key columns are returned by default.
//SearchRequest.ColumnsToGet columnsToGet = new SearchRequest.ColumnsToGet();
//columnsToGet.setReturnAll(true); // Set this to return all columns.
//columnsToGet.setColumns(Arrays.asList("ColName1","ColName2")); // Set this to return specified columns.
//searchRequest.setColumnsToGet(columnsToGet);
SearchResponse resp = client.search(searchRequest);
//System.out.println("TotalCount: " + resp.getTotalCount()); // Print the total number of matched rows, not the number of returned rows.
System.out.println("Row: " + resp.getRows());
}
Contoh kueri di mana baris anak berbeda memenuhi beberapa kondisi
Contoh berikut mengkueri baris di mana objek nested dalam bidang `col_nested` memenuhi dua kondisi: col_nested.col_keyword adalah "tablestore" dan col_nested.col_long tidak kosong.
Berdasarkan data sampel, data di baris 1 dan baris 2 memenuhi kondisi kueri.
public static void nestedQuery(SyncClient client) {
// Condition 1: The value of the col_keyword column in the child row of col_nested must be "tablestore".
TermQuery termQuery = new TermQuery();
termQuery.setFieldName("col_nested.col_keyword");
termQuery.setTerm(ColumnValue.fromString("tablestore"));
NestedQuery nestedTermQuery = new NestedQuery();
nestedTermQuery.setPath("col_nested");
nestedTermQuery.setScoreMode(ScoreMode.None);
nestedTermQuery.setQuery(termQuery);
// Condition 2: The col_long column in the child row of col_nested must not be empty.
ExistsQuery existsQuery = new ExistsQuery();
existsQuery.setFieldName("col_nested.col_long");
NestedQuery nestedExistsQuery = new NestedQuery();
nestedExistsQuery.setPath("col_nested");
nestedExistsQuery.setScoreMode(ScoreMode.None);
nestedExistsQuery.setQuery(existsQuery);
// Use the AND condition of BoolQuery to query for rows that meet the preceding conditions.
List<Query> mustQueries = new ArrayList<>();
mustQueries.add(nestedTermQuery);
mustQueries.add(nestedExistsQuery);
// The BoolQuery includes multiple NestedQuery conditions. The query is successful if different child rows meet the respective query conditions.
BoolQuery boolQuery = new BoolQuery();
boolQuery.setMustQueries(mustQueries);
SearchQuery searchQuery = new SearchQuery();
searchQuery.setQuery(boolQuery);
SearchRequest searchRequest = new SearchRequest("<TABLE_NAME>", "<SEARCH_INDEX_NAME>", searchQuery);
// Use the columnsToGet parameter to specify the columns to return or to return all columns. If you do not set this parameter, only the primary key columns are returned by default.
//SearchRequest.ColumnsToGet columnsToGet = new SearchRequest.ColumnsToGet();
//columnsToGet.setReturnAll(true); // Set this to return all columns.
//columnsToGet.setColumns(Arrays.asList("ColName1","ColName2")); // Set this to return specified columns.
//searchRequest.setColumnsToGet(columnsToGet);
SearchResponse resp = client.search(searchRequest);
//System.out.println("TotalCount: " + resp.getTotalCount()); // Print the total number of matched rows, not the number of returned rows.
System.out.println("Row: " + resp.getRows());
}
Contoh penggunaan ringkasan dan penyorotan dalam kueri bersarang
Contoh berikut menunjukkan cara menggunakan `NestedQuery` untuk mengkueri data di mana nilai sub-field `Level1_Col1_Nested` dalam bidang nested `Col_Nested` cocok dengan `hangzhou shanghai. Kueri pencarian disorot dalam hasil yang dikembalikan.
/**
* Use summary and highlighting in a NestedQuery. Set parameters using innerHits.
*/
public static void nestedQueryWithHighlighting(SyncClient client) {
SearchRequest searchRequest = SearchRequest.newBuilder()
.tableName("<TABLE_NAME>")
.indexName("<SEARCH_INDEX_NAME>")
.returnAllColumnsFromIndex(true)
.searchQuery(SearchQuery.newBuilder()
.limit(5)
.query(QueryBuilders.nested()
.path("Col_Nested")
.scoreMode(ScoreMode.Min)
.query(QueryBuilders.match("Col_Nested.Level1_Col1_Nested", "hangzhou shanghai"))
.innerHits(InnerHits.newBuilder()
.highlight(Highlight.newBuilder()
.addFieldHighlightParam("Col_Nested.Level1_Col1_Nested", HighlightParameter.newBuilder().build())
.build())
.build()))
.build())
.build();
SearchResponse resp = client.search(searchRequest);
// Print the highlighted results.
printSearchHit(resp.getSearchHits(), "");
}
/**
* Print the content of searchHit.
* @param searchHits The search hits.
* @param prefix The prefix to add when printing nested structures to show hierarchical information.
*/
private static void printSearchHit(List<SearchHit> searchHits, String prefix) {
for (SearchHit searchHit : searchHits) {
if (searchHit.getScore() != null) {
System.out.printf("%s Score: %s\n", prefix, searchHit.getScore());
}
if (searchHit.getOffset() != null) {
System.out.printf("%s Offset: %s\n", prefix, searchHit.getOffset());
}
if (searchHit.getRow() != null) {
System.out.printf("%s Row: %s\n", prefix, searchHit.getRow().toString());
}
// Print the highlighted fragments for each field.
if (searchHit.getHighlightResultItem() != null) {
System.out.printf("%s Highlight: \n", prefix);
StringBuilder strBuilder = new StringBuilder();
for (Map.Entry<String, HighlightField> entry : searchHit.getHighlightResultItem().getHighlightFields().entrySet()) {
strBuilder.append(entry.getKey()).append(":").append("[");
strBuilder.append(StringUtils.join(",", entry.getValue().getFragments())).append("]\n");
}
System.out.printf("%s %s", prefix, strBuilder);
}
// Highlighted results for the nested type.
for (SearchInnerHit searchInnerHit : searchHit.getSearchInnerHits().values()) {
System.out.printf("%s Path: %s\n", prefix, searchInnerHit.getPath());
System.out.printf("%s InnerHit: \n", prefix);
printSearchHit(searchInnerHit.getSubSearchHits(), prefix + " ");
}
System.out.println();
}
}
Asumsikan bahwa bidang nested multi-level `Col_Nested` mencakup dua sub-field: `Level1_Col1_Text` (Text) dan `Level1_Col2_Nested` (Nested). Bidang nested `Level1_Col2_Nested` mencakup sub-field `Level2_Col1_Text`.
Contoh berikut menunjukkan cara menambahkan `BoolQuery` ke `NestedQuery` untuk menggunakan fitur ringkasan dan penyorotan pada sub-field `Level1_Col1_Text` dalam bidang `Col_Nested` dan sub-field `Level2_Col1_Text` di bawah `Level1_Col2_Nested`.
public static void nestedQueryWithHighlighting(SyncClient client) {
SearchRequest searchRequest = SearchRequest.newBuilder()
.tableName("<TABLE_NAME>")
.indexName("<SEARCH_INDEX_NAME>")
.returnAllColumnsFromIndex(true)
.searchQuery(SearchQuery.newBuilder()
.limit(5)
.query(QueryBuilders.nested()
.path("Col_Nested")
.scoreMode(ScoreMode.Min)
.query(QueryBuilders.bool()
.should(QueryBuilders.match("Col_Nested.Level1_Col1_Text", "hangzhou shanghai"))
.should(QueryBuilders.nested()
.path("Col_Nested.Level1_Col2_Nested")
.scoreMode(ScoreMode.Min)
.query(QueryBuilders.match("Col_Nested.Level1_Col2_Nested.Level2_Col1_Text", "hangzhou shanghai"))
.innerHits(InnerHits.newBuilder()
.highlight(Highlight.newBuilder()
.addFieldHighlightParam("Col_Nested.Level1_Col2_Nested.Level2_Col1_Text", HighlightParameter.newBuilder().build())
.build())
.build())))
.innerHits(InnerHits.newBuilder()
.sort(new Sort(Arrays.asList(
new ScoreSort(),
new DocSort()
)))
.highlight(Highlight.newBuilder()
.addFieldHighlightParam("Col_Nested.Level1_Col1_Text", HighlightParameter.newBuilder().build())
.build())
.build()))
.build())
.build();
SearchResponse resp = client.search(searchRequest);
// Print the highlighted results.
printSearchHit(resp.getSearchHits(), "");
}
/**
* Print the content of searchHit.
* @param searchHits The search hits.
* @param prefix The prefix to add when printing nested structures to show hierarchical information.
*/
private static void printSearchHit(List<SearchHit> searchHits, String prefix) {
for (SearchHit searchHit : searchHits) {
if (searchHit.getScore() != null) {
System.out.printf("%s Score: %s\n", prefix, searchHit.getScore());
}
if (searchHit.getOffset() != null) {
System.out.printf("%s Offset: %s\n", prefix, searchHit.getOffset());
}
if (searchHit.getRow() != null) {
System.out.printf("%s Row: %s\n", prefix, searchHit.getRow().toString());
}
// Print the highlighted fragments for each field.
if (searchHit.getHighlightResultItem() != null) {
System.out.printf("%s Highlight: \n", prefix);
StringBuilder strBuilder = new StringBuilder();
for (Map.Entry<String, HighlightField> entry : searchHit.getHighlightResultItem().getHighlightFields().entrySet()) {
strBuilder.append(entry.getKey()).append(":").append("[");
strBuilder.append(StringUtils.join(",", entry.getValue().getFragments())).append("]\n");
}
System.out.printf("%s %s", prefix, strBuilder);
}
// Highlighted results for the nested type.
for (SearchInnerHit searchInnerHit : searchHit.getSearchInnerHits().values()) {
System.out.printf("%s Path: %s\n", prefix, searchInnerHit.getPath());
System.out.printf("%s InnerHit: \n", prefix);
printSearchHit(searchInnerHit.getSubSearchHits(), prefix + " ");
}
System.out.println();
}
}