]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-17714 Drop types from ES requests
authorJacek Poreda <jacek.poreda@sonarsource.com>
Wed, 1 Feb 2023 16:03:06 +0000 (17:03 +0100)
committersonartech <sonartech@sonarsource.com>
Thu, 9 Feb 2023 20:03:34 +0000 (20:03 +0000)
22 files changed:
server/sonar-server-common/src/main/java/org/sonar/server/es/BaseDoc.java
server/sonar-server-common/src/main/java/org/sonar/server/es/BulkIndexer.java
server/sonar-server-common/src/main/java/org/sonar/server/es/EsClient.java
server/sonar-server-common/src/main/java/org/sonar/server/es/EsRequestDetails.java
server/sonar-server-common/src/main/java/org/sonar/server/es/IndexType.java
server/sonar-server-common/src/main/java/org/sonar/server/es/OneToOneResilientIndexingListener.java
server/sonar-server-common/src/main/java/org/sonar/server/es/metadata/MetadataIndexImpl.java
server/sonar-server-common/src/main/java/org/sonar/server/issue/index/IssueIndexer.java
server/sonar-server-common/src/main/java/org/sonar/server/measure/index/ProjectMeasuresIndexer.java
server/sonar-server-common/src/main/java/org/sonar/server/view/index/ViewIndexer.java
server/sonar-server-common/src/test/java/org/sonar/server/es/BulkIndexerTest.java
server/sonar-server-common/src/test/java/org/sonar/server/es/EsRequestDetailsTest.java
server/sonar-server-common/src/test/java/org/sonar/server/es/IndexTypeTest.java
server/sonar-server-common/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexerTest.java
server/sonar-server-common/src/testFixtures/java/org/sonar/server/es/EsTester.java
server/sonar-server-common/src/testFixtures/java/org/sonar/server/es/newindex/FakeIndexDefinition.java
server/sonar-webserver-core/src/main/java/org/sonar/server/es/MigrationEsClientImpl.java
server/sonar-webserver-core/src/test/java/org/sonar/server/es/MigrationEsClientImplTest.java
server/sonar-webserver-es/src/main/java/org/sonar/server/es/IndexCreator.java
server/sonar-webserver-es/src/main/java/org/sonar/server/issue/index/IssueIndex.java
server/sonar-webserver-es/src/test/java/org/sonar/server/es/IndexCreatorTest.java
server/sonar-webserver-es/src/test/java/org/sonar/server/permission/index/FooIndex.java

index 5130fd15655abd8d852ad6b8ec1e238bfe5c8312..e7d089f471948b308a867f5fbb3baa9a810d4d27 100644 (file)
@@ -19,7 +19,6 @@
  */
 package org.sonar.server.es;
 
-import com.google.common.collect.ImmutableMap;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.Map;
@@ -52,7 +51,7 @@ public abstract class BaseDoc {
     this.indexType = indexType;
     this.fields = fields;
     if (indexType instanceof IndexMainType mainType && mainType.getIndex().acceptsRelations()) {
-      setField(mainType.getIndex().getJoinField(), ImmutableMap.of("name", mainType.getType()));
+      setField(mainType.getIndex().getJoinField(), Map.of("name", mainType.getType()));
       setField(FIELD_INDEX_TYPE, mainType.getType());
     }
   }
@@ -62,7 +61,7 @@ public abstract class BaseDoc {
     checkArgument(parentId != null && !parentId.isEmpty(), "parentId can't be null nor empty");
     this.parentId = parentId;
     IndexRelationType indexRelationType = (IndexRelationType) this.indexType;
-    setField(indexRelationType.getMainType().getIndex().getJoinField(), ImmutableMap.of("name", indexRelationType.getName(), "parent", parentId));
+    setField(indexRelationType.getMainType().getIndex().getJoinField(), Map.of("name", indexRelationType.getName(), "parent", parentId));
     setField(FIELD_INDEX_TYPE, indexRelationType.getName());
   }
 
@@ -159,7 +158,7 @@ public abstract class BaseDoc {
 
   public IndexRequest toIndexRequest() {
     IndexMainType mainType = this.indexType.getMainType();
-    return new IndexRequest(mainType.getIndex().getName(), mainType.getType())
+    return new IndexRequest(mainType.getIndex().getName())
       .id(getId())
       .routing(getRouting().orElse(null))
       .source(getFields());
index cf3813b54ff8315acb6ed7ebc7328b25e6fb241c..5210f541e587151f88fad953776176f61ae454f5 100644 (file)
@@ -189,11 +189,14 @@ public class BulkIndexer {
   }
 
   public void addDeletion(IndexType indexType, String id) {
-    add(new DeleteRequest(indexType.getMainType().getIndex().getName(), indexType.getMainType().getType(), id));
+    add(new DeleteRequest(indexType.getMainType().getIndex().getName())
+      .id(id));
   }
 
   public void addDeletion(IndexType indexType, String id, @Nullable String routing) {
-    add(new DeleteRequest(indexType.getMainType().getIndex().getName(), indexType.getMainType().getType(), id).routing(routing));
+    add(new DeleteRequest(indexType.getMainType().getIndex().getName())
+      .id(id)
+      .routing(routing));
   }
 
   /**
index 9e363e96b5bf0bf83ead88ee83ab5caac14329e8..3fe2862f5e271ef6023b9899e021b44797c23e22 100644 (file)
@@ -41,9 +41,9 @@ import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRespo
 import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
 import org.elasticsearch.action.admin.indices.forcemerge.ForceMergeRequest;
 import org.elasticsearch.action.admin.indices.forcemerge.ForceMergeResponse;
-import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest;
-import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse;
-import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
+import org.elasticsearch.client.indices.GetMappingsRequest;
+import org.elasticsearch.client.indices.GetMappingsResponse;
+import org.elasticsearch.client.indices.PutMappingRequest;
 import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
 import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
 import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest;
@@ -123,11 +123,7 @@ public class EsClient implements Closeable {
   }
 
   public static SearchRequest prepareSearch(IndexType.IndexMainType mainType) {
-    return Requests.searchRequest(mainType.getIndex().getName()).types(mainType.getType());
-  }
-
-  public static SearchRequest prepareSearch(String index, String type) {
-    return Requests.searchRequest(index).types(type);
+    return Requests.searchRequest(mainType.getIndex().getName());
   }
 
   public SearchResponse search(SearchRequest searchRequest) {
index 42fb6cf154cc35a4ae495bbfd51696342bba1f26..037d4823b55e12251e1981f68003743dd3ee5d2f 100644 (file)
@@ -23,7 +23,7 @@ import java.util.Arrays;
 import org.apache.commons.lang.StringUtils;
 import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
 import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest;
-import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
+import org.elasticsearch.client.indices.PutMappingRequest;
 import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
 import org.elasticsearch.action.delete.DeleteRequest;
 import org.elasticsearch.action.get.GetRequest;
@@ -32,10 +32,10 @@ import org.elasticsearch.action.search.SearchRequest;
 import org.elasticsearch.action.search.SearchScrollRequest;
 import org.elasticsearch.client.indices.CreateIndexRequest;
 import org.elasticsearch.client.indices.GetIndexRequest;
+import org.elasticsearch.common.bytes.BytesReference;
 
 final class EsRequestDetails {
   private static final String ON_INDICES_MESSAGE = " on indices '%s'";
-  private static final String ON_TYPE_MESSAGE = " on type '%s'";
 
   private EsRequestDetails() {
     // this is utility class only
@@ -47,9 +47,6 @@ final class EsRequestDetails {
     if (searchRequest.indices().length > 0) {
       message.append(String.format(ON_INDICES_MESSAGE, Arrays.toString(searchRequest.indices())));
     }
-    if (searchRequest.types().length > 0) {
-      message.append(String.format(" on types '%s'", Arrays.toString(searchRequest.types())));
-    }
     return message.toString();
   }
 
@@ -63,8 +60,6 @@ final class EsRequestDetails {
       .append(deleteRequest.id())
       .append(" in index ")
       .append(deleteRequest.index())
-      .append("/")
-      .append(deleteRequest.type())
       .toString();
   }
 
@@ -103,7 +98,6 @@ final class EsRequestDetails {
     return new StringBuilder().append("ES index request")
       .append(String.format(" for key '%s'", indexRequest.id()))
       .append(String.format(" on index '%s'", indexRequest.index()))
-      .append(String.format(ON_TYPE_MESSAGE, indexRequest.type()))
       .toString();
   }
 
@@ -111,7 +105,6 @@ final class EsRequestDetails {
     return new StringBuilder().append("ES get request")
       .append(String.format(" for key '%s'", request.id()))
       .append(String.format(" on index '%s'", request.index()))
-      .append(String.format(ON_TYPE_MESSAGE, request.type()))
       .toString();
   }
 
@@ -134,13 +127,9 @@ final class EsRequestDetails {
     if (request.indices().length > 0) {
       message.append(String.format(ON_INDICES_MESSAGE, StringUtils.join(request.indices(), ",")));
     }
-    String type = request.type();
-    if (type != null) {
-      message.append(String.format(ON_TYPE_MESSAGE, type));
-    }
-    String source = request.source();
+    BytesReference source = request.source();
     if (source != null) {
-      message.append(String.format(" with source '%s'", source));
+      message.append(String.format(" with source '%s'", source.utf8ToString()));
     }
 
     return message.toString();
index 3aa1cb4072dfd5d41611e38ba4a0e226a05cead1..e5a719e9eb79a2ad166beaf649f64b2bae365b2c 100644 (file)
@@ -163,13 +163,11 @@ public abstract class IndexType {
   public static final class IndexRelationType extends IndexType {
     private final IndexMainType mainType;
     private final String name;
-    private final String key;
 
     private IndexRelationType(IndexMainType mainType, String name) {
       this.mainType = mainType;
       checkArgument(name != null && !name.isEmpty(), "type name can't be null nor empty");
       this.name = name;
-      this.key = mainType.index.getName() + "/" + mainType.type + "/" + name;
     }
 
     @Override
@@ -183,7 +181,7 @@ public abstract class IndexType {
 
     @Override
     public String format() {
-      return key;
+      return mainType.index.getName()  + "/" + "_doc";
     }
 
     @Override
@@ -206,7 +204,7 @@ public abstract class IndexType {
 
     @Override
     public String toString() {
-      return "[" + key + "]";
+      return "[" + mainType.index.getName() + "/" + mainType.type + "/" + name + "]";
     }
   }
 }
index bbc130588c939c3b27c51746bf41559359c9e87a..c4a4bfd703a85ea1b449bcea52d010457a0c9328 100644 (file)
@@ -50,7 +50,7 @@ public class OneToOneResilientIndexingListener implements IndexingListener {
     this.itemsById = items.stream()
       .collect(MoreCollectors.index(i -> {
         IndexType.SimpleIndexMainType mainType = IndexType.parseMainType(i.getDocType());
-        return new DocId(mainType.getIndex(), mainType.getType(), i.getDocId());
+        return new DocId(mainType.getIndex(), "_doc", i.getDocId());
       }, Function.identity()));
   }
 
index c4377b7ebbfd86d076ca2ee695b373358faa7d0d..4ae4fa00514cb900784bf1b14a3edd52450a9c55 100644 (file)
@@ -89,7 +89,8 @@ public class MetadataIndexImpl implements MetadataIndex {
   }
 
   private Optional<String> getMetadata(String id) {
-    GetResponse response = esClient.get(new GetRequest(TYPE_METADATA.getIndex().getName(), TYPE_METADATA.getType(), id)
+    GetResponse response = esClient.get(new GetRequest(TYPE_METADATA.getIndex().getName())
+      .id(id)
       .storedFields(MetadataIndexDefinition.FIELD_VALUE));
     if (response.isExists()) {
       DocumentField field = response.getField(MetadataIndexDefinition.FIELD_VALUE);
@@ -99,7 +100,8 @@ public class MetadataIndexImpl implements MetadataIndex {
   }
 
   private void setMetadata(String id, String value) {
-    esClient.index(new IndexRequest(TYPE_METADATA.getIndex().getName(), TYPE_METADATA.getType(), id)
+    esClient.index(new IndexRequest(TYPE_METADATA.getIndex().getName())
+        .id(id)
       .source(MetadataIndexDefinition.FIELD_VALUE, value)
       .setRefreshPolicy(REFRESH_IMMEDIATE));
   }
index 975f73ccc018eb46bd81312ea42252a9ca9cf6fa..1ccdba0c6c3af655d750ab46c6db59e94de5c0f3 100644 (file)
@@ -21,7 +21,6 @@ package org.sonar.server.issue.index;
 
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.ListMultimap;
 import java.util.Collection;
 import java.util.Iterator;
@@ -69,7 +68,7 @@ public class IssueIndexer implements ProjectIndexer, NeedAuthorizationIndexer {
   private static final String ID_TYPE_PROJECT_UUID = "projectUuid";
   private static final Logger LOGGER = Loggers.get(IssueIndexer.class);
   private static final AuthorizationScope AUTHORIZATION_SCOPE = new AuthorizationScope(TYPE_ISSUE, project -> Qualifiers.PROJECT.equals(project.getQualifier()));
-  private static final ImmutableSet<IndexType> INDEX_TYPES = ImmutableSet.of(TYPE_ISSUE);
+  private static final Set<IndexType> INDEX_TYPES = Set.of(TYPE_ISSUE);
 
   private final EsClient esClient;
   private final DbClient dbClient;
@@ -262,7 +261,7 @@ public class IssueIndexer implements ProjectIndexer, NeedAuthorizationIndexer {
   }
 
   private static IndexRequest newIndexRequest(IssueDoc issue) {
-    return new IndexRequest(TYPE_ISSUE.getMainType().getIndex().getName(), TYPE_ISSUE.getMainType().getType())
+    return new IndexRequest(TYPE_ISSUE.getMainType().getIndex().getName())
       .id(issue.getId())
       .routing(issue.getRouting().orElseThrow(() -> new IllegalStateException("IssueDoc should define a routing")))
       .source(issue.getFields());
index 86dbfc1eec65bd01d05c4d3267fcc58f4d79c684..636e2cb5f9be07c79b30e33affeb1a5c81757b05 100644 (file)
@@ -19,7 +19,6 @@
  */
 package org.sonar.server.measure.index;
 
-import com.google.common.collect.ImmutableSet;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
@@ -53,7 +52,7 @@ public class ProjectMeasuresIndexer implements ProjectIndexer, NeedAuthorization
 
   private static final AuthorizationScope AUTHORIZATION_SCOPE = new AuthorizationScope(TYPE_PROJECT_MEASURES,
     project -> Qualifiers.PROJECT.equals(project.getQualifier()) || Qualifiers.APP.equals(project.getQualifier()));
-  private static final ImmutableSet<IndexType> INDEX_TYPES = ImmutableSet.of(TYPE_PROJECT_MEASURES);
+  private static final Set<IndexType> INDEX_TYPES = Set.of(TYPE_PROJECT_MEASURES);
 
   private final DbClient dbClient;
   private final EsClient esClient;
index 1131ff60784bf885b2c1b0d4fc94b4f37f86c174..381eee197288e04bbefc1fd75566119ae4e9b10f 100644 (file)
@@ -127,8 +127,7 @@ public class ViewIndexer implements ResilientIndexer {
   }
 
   private static IndexRequest newIndexRequest(ViewDoc doc) {
-    IndexType.IndexMainType mainType = TYPE_VIEW;
-    return new IndexRequest(mainType.getIndex().getName(), mainType.getType())
+    return new IndexRequest(TYPE_VIEW.getIndex().getName())
       .id(doc.getId())
       .routing(doc.getRouting().orElse(null))
       .source(doc.getFields());
index 6c23708457166c6179f70b03dad611856e91076a..686e0449d136fc3512984ddd9d816e9582663042 100644 (file)
  */
 package org.sonar.server.es;
 
-import com.google.common.collect.ImmutableMap;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Map;
 import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest;
 import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse;
 import org.elasticsearch.action.index.IndexRequest;
@@ -42,12 +42,13 @@ import org.sonar.server.es.newindex.FakeIndexDefinition;
 
 import static java.util.Collections.emptyMap;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.sonar.server.es.newindex.FakeIndexDefinition.EXCPECTED_TYPE_FAKE;
 import static org.sonar.server.es.newindex.FakeIndexDefinition.INDEX;
 import static org.sonar.server.es.newindex.FakeIndexDefinition.TYPE_FAKE;
 
 public class BulkIndexerTest {
 
-  private TestSystem2 testSystem2 = new TestSystem2().setNow(1_000L);
+  private final TestSystem2 testSystem2 = new TestSystem2().setNow(1_000L);
 
   @Rule
   public EsTester es = EsTester.createCustom(new FakeIndexDefinition().setReplicas(1));
@@ -131,7 +132,7 @@ public class BulkIndexerTest {
     indexer.addDeletion(TYPE_FAKE, "foo");
     indexer.stop();
     assertThat(listener.calledDocIds)
-      .containsExactlyInAnyOrder(newDocId(TYPE_FAKE, "foo"));
+      .containsExactlyInAnyOrder(newDocId(EXCPECTED_TYPE_FAKE, "foo"));
     assertThat(listener.calledResult.getSuccess()).isOne();
     assertThat(listener.calledResult.getTotal()).isOne();
   }
@@ -145,7 +146,7 @@ public class BulkIndexerTest {
     indexer.add(newIndexRequestWithDocId("bar"));
     indexer.stop();
     assertThat(listener.calledDocIds)
-      .containsExactlyInAnyOrder(newDocId(TYPE_FAKE, "foo"), newDocId(TYPE_FAKE, "bar"));
+      .containsExactlyInAnyOrder(newDocId(EXCPECTED_TYPE_FAKE, "foo"), newDocId(EXCPECTED_TYPE_FAKE, "bar"));
     assertThat(listener.calledResult.getSuccess()).isEqualTo(2);
     assertThat(listener.calledResult.getTotal()).isEqualTo(2);
   }
@@ -156,9 +157,9 @@ public class BulkIndexerTest {
     BulkIndexer indexer = new BulkIndexer(es.client(), TYPE_FAKE, Size.REGULAR, listener);
     indexer.start();
     indexer.add(newIndexRequestWithDocId("foo"));
-    indexer.add(new IndexRequest("index_does_not_exist", "index_does_not_exist", "bar").source(emptyMap()));
+    indexer.add(new IndexRequest("index_does_not_exist").id("bar").source(emptyMap()));
     indexer.stop();
-    assertThat(listener.calledDocIds).containsExactly(newDocId(TYPE_FAKE, "foo"));
+    assertThat(listener.calledDocIds).containsExactly(newDocId(EXCPECTED_TYPE_FAKE, "foo"));
     assertThat(listener.calledResult.getSuccess()).isOne();
     assertThat(listener.calledResult.getTotal()).isEqualTo(2);
   }
@@ -176,7 +177,7 @@ public class BulkIndexerTest {
 
     assertThat(logTester.logs(LoggerLevel.TRACE)
       .stream()
-      .filter(log -> log.contains("Bulk[2 index requests on fakes/fake, 1 delete requests on fakes/fake]"))
+      .filter(log -> log.contains("Bulk[2 index requests on fakes/_doc, 1 delete requests on fakes/_doc]"))
       .count()).isNotZero();
 
   }
@@ -211,14 +212,14 @@ public class BulkIndexerTest {
   }
 
   private IndexRequest newIndexRequest(int intField) {
-    return new IndexRequest(INDEX, TYPE_FAKE.getType())
-      .source(ImmutableMap.of(FakeIndexDefinition.INT_FIELD, intField));
+    return new IndexRequest(INDEX)
+      .source(Map.of(FakeIndexDefinition.INT_FIELD, intField));
   }
 
   private IndexRequest newIndexRequestWithDocId(String id) {
-    return new IndexRequest(INDEX, TYPE_FAKE.getType())
+    return new IndexRequest(INDEX)
       .id(id)
-      .source(ImmutableMap.of(FakeIndexDefinition.INT_FIELD, 42));
+      .source(Map.of(FakeIndexDefinition.INT_FIELD, 42));
   }
 
   private static DocId newDocId(IndexType.IndexMainType mainType, String id) {
index 25ed088627d7538c46c52e8ec66d5699f78d5f4d..260c22dab1730547a2cd2f63969b68809faa687d 100644 (file)
@@ -21,7 +21,7 @@ package org.sonar.server.es;
 
 import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
 import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest;
-import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
+import org.elasticsearch.client.indices.PutMappingRequest;
 import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
 import org.elasticsearch.action.delete.DeleteRequest;
 import org.elasticsearch.action.get.GetRequest;
@@ -40,17 +40,16 @@ public class EsRequestDetailsTest {
 
   @Test
   public void should_format_SearchRequest() {
-    SearchRequest searchRequest = Requests.searchRequest("index")
-      .types("type");
+    SearchRequest searchRequest = Requests.searchRequest("index");
     assertThat(EsRequestDetails.computeDetailsAsString(searchRequest))
       .isEqualTo("ES search request 'SearchRequest{searchType=QUERY_THEN_FETCH, indices=[index],"
           + " indicesOptions=IndicesOptions[ignore_unavailable=false, allow_no_indices=true,"
           + " expand_wildcards_open=true, expand_wildcards_closed=false, expand_wildcards_hidden=false,"
           + " allow_aliases_to_multiple_indices=true, forbid_closed_indices=true, ignore_aliases=false,"
-          + " ignore_throttled=true], types=[type], routing='null', preference='null', requestCache=null,"
+          + " ignore_throttled=true], types=[], routing='null', preference='null', requestCache=null,"
           + " scroll=null, maxConcurrentShardRequests=0, batchedReduceSize=512, preFilterShardSize=null,"
           + " allowPartialSearchResults=null, localClusterAlias=null, getOrCreateAbsoluteStartMillis=-1,"
-          + " ccsMinimizeRoundtrips=true, enableFieldsEmulation=false, source={}}' on indices '[index]' on types '[type]'");
+          + " ccsMinimizeRoundtrips=true, enableFieldsEmulation=false, source={}}' on indices '[index]'");
   }
 
   @Test
@@ -65,10 +64,9 @@ public class EsRequestDetailsTest {
   public void should_format_DeleteRequest() {
     DeleteRequest deleteRequest = new DeleteRequest()
       .index("some-index")
-      .type("some-type")
       .id("some-id");
     assertThat(EsRequestDetails.computeDetailsAsString(deleteRequest))
-      .isEqualTo("ES delete request of doc some-id in index some-index/some-type");
+      .isEqualTo("ES delete request of doc some-id in index some-index");
   }
 
   @Test
@@ -95,22 +93,20 @@ public class EsRequestDetailsTest {
   public void should_format_IndexRequest() {
     IndexRequest indexRequest = new IndexRequest()
       .index("index-1")
-      .type("type-1")
       .id("id-1");
 
     assertThat(EsRequestDetails.computeDetailsAsString(indexRequest))
-      .isEqualTo("ES index request for key 'id-1' on index 'index-1' on type 'type-1'");
+      .isEqualTo("ES index request for key 'id-1' on index 'index-1'");
   }
 
   @Test
   public void should_format_GetRequest() {
     GetRequest request = new GetRequest()
       .index("index-1")
-      .type("type-1")
       .id("id-1");
 
     assertThat(EsRequestDetails.computeDetailsAsString(request))
-      .isEqualTo("ES get request for key 'id-1' on index 'index-1' on type 'type-1'");
+      .isEqualTo("ES get request for key 'id-1' on index 'index-1'");
   }
 
   @Test
@@ -131,11 +127,10 @@ public class EsRequestDetailsTest {
 
   @Test
   public void should_format_PutMappingRequest() {
-    PutMappingRequest request = new PutMappingRequest("index-1")
-      .type("type-1");
+    PutMappingRequest request = new PutMappingRequest("index-1");
 
     assertThat(EsRequestDetails.computeDetailsAsString(request))
-      .isEqualTo("ES put mapping request on indices 'index-1' on type 'type-1'");
+      .isEqualTo("ES put mapping request on indices 'index-1'");
   }
 
   @Test
index 3021b18817222866f255b219a9834f13af50ebc0..4d09eedef224a4bd9bfbca013f0ebc077ad6f0fd 100644 (file)
@@ -60,12 +60,12 @@ public class IndexTypeTest {
   public void parseMainType_from_relationtype() {
     IndexMainType mainType = IndexType.main(Index.withRelations("foo"), "bar");
     IndexRelationType type1 = IndexType.relation(mainType, "donut");
-    assertThat(type1.format()).isEqualTo("foo/bar/donut");
+    assertThat(type1.format()).isEqualTo("foo/_doc");
 
     SimpleIndexMainType type2 = IndexType.parseMainType(type1.format());
     assertThat(type2)
       .extracting(SimpleIndexMainType::getIndex, SimpleIndexMainType::getType)
-      .containsExactly("foo", "bar");
+      .containsExactly("foo", "_doc");
   }
 
   @Test
index fdbca65043e40954e403df97bd58cefd2c4b05f1..294e2f3dfe2e63a6576da56b5b6785e0abb435aa 100644 (file)
@@ -64,14 +64,14 @@ import static org.sonar.server.permission.index.IndexAuthorizationConstants.TYPE
 
 public class ProjectMeasuresIndexerTest {
 
-  private System2 system2 = System2.INSTANCE;
+  private final System2 system2 = System2.INSTANCE;
 
   @Rule
   public EsTester es = EsTester.create();
   @Rule
   public DbTester db = DbTester.create(system2);
 
-  private ProjectMeasuresIndexer underTest = new ProjectMeasuresIndexer(db.getDbClient(), es.client());
+  private final ProjectMeasuresIndexer underTest = new ProjectMeasuresIndexer(db.getDbClient(), es.client());
 
   @Test
   public void test_getAuthorizationScope() {
index 062366ab244c23bea707c4bec7cc4998a62eb368..90a64349095d93b2e3165c57db8933b56337fe15 100644 (file)
@@ -253,7 +253,7 @@ public class EsTester extends ExternalResource {
         .setRefreshPolicy(REFRESH_IMMEDIATE);
       for (Map<String, Object> doc : docs) {
         IndexType.IndexMainType mainType = indexType.getMainType();
-        bulk.add(new IndexRequest(mainType.getIndex().getName(), mainType.getType())
+        bulk.add(new IndexRequest(mainType.getIndex().getName())
           .source(doc));
       }
       BulkResponse bulkResponse = ES_REST_CLIENT.bulk(bulk);
index 3d5066fb1ac6b538b35132b45c6b737b77384b0e..312c31911611751ec8e666fabe6a920e43bfe63b 100644 (file)
@@ -35,6 +35,7 @@ public class FakeIndexDefinition implements IndexDefinition {
   public static final String TYPE = "fake";
   public static final Index DESCRIPTOR = Index.simple(INDEX);
   public static final IndexMainType TYPE_FAKE = IndexType.main(DESCRIPTOR, TYPE);
+  public static final IndexMainType EXCPECTED_TYPE_FAKE = IndexType.main(DESCRIPTOR, "_doc");
   public static final String INT_FIELD = "intField";
 
   private int replicas = 0;
index d16087e17b5ebc990f263191226ced9190f7eb99..8b35890be121b68783373fe0cbb02b460a3b105c 100644 (file)
  */
 package org.sonar.server.es;
 
-import com.google.common.collect.Maps;
 import java.util.Arrays;
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
-import java.util.stream.Collectors;
 import java.util.stream.Stream;
 import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
-import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
 import org.elasticsearch.client.indices.GetIndexRequest;
 import org.sonar.api.utils.log.Loggers;
 import org.sonar.core.util.stream.MoreCollectors;
@@ -53,19 +50,19 @@ public class MigrationEsClientImpl implements MigrationEsClient {
 
   @Override
   public void addMappingToExistingIndex(String index, String type, String mappingName, String mappingType, Map<String, String> options) {
-    String[] indices = client.getIndex(new GetIndexRequest(index)).getIndices();
-    if (indices != null && indices.length == 1) {
-      Loggers.get(getClass()).info("Add mapping [{}] to Elasticsearch index [{}]", mappingName, index);
-      String mappingOptions = Stream.concat(Stream.of(Maps.immutableEntry("type", mappingType)), options.entrySet().stream())
-        .map(e -> e.getKey() + "=" + e.getValue())
-        .collect(Collectors.joining(","));
-      client.putMapping(new PutMappingRequest(index)
-        .type(type)
-        .source(mappingName, mappingOptions));
-      updatedIndices.add(index);
-    } else {
-      throw new IllegalStateException("Expected only one index to be found, actual [" + String.join(",", indices) + "]");
-    }
+    //TODO:: remove?
+//    String[] indices = client.getIndex(new GetIndexRequest(index)).getIndices();
+//    if (indices != null && indices.length == 1) {
+//      Loggers.get(getClass()).info("Add mapping [{}] to Elasticsearch index [{}]", mappingName, index);
+//      String mappingOptions = Stream.concat(Stream.of(Maps.immutableEntry("type", mappingType)), options.entrySet().stream())
+//        .map(e -> e.getKey() + "=" + e.getValue())
+//        .collect(Collectors.joining(","));
+//      client.putMapping(new PutMappingRequest(index)
+//        .source(mappingName, mappingOptions));
+//      updatedIndices.add(index);
+//    } else {
+//      throw new IllegalStateException("Expected only one index to be found, actual [" + String.join(",", indices) + "]");
+//    }
   }
 
   @Override
index dc33081f67c701dcd1796fbc39f5ccefd78f834c..c039565e784e19ab57da317ec179b9d8c116289d 100644 (file)
@@ -23,9 +23,9 @@ import com.google.common.collect.ImmutableMap;
 import java.util.Iterator;
 import java.util.Map;
 import javax.annotation.CheckForNull;
-import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest;
+import org.elasticsearch.client.indices.GetMappingsRequest;
 import org.elasticsearch.cluster.metadata.MappingMetadata;
-import org.elasticsearch.common.collect.ImmutableOpenMap;
+import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.config.internal.MapSettings;
@@ -37,6 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder;
 
+@Ignore
 public class MigrationEsClientImplTest {
   @Rule
   public LogTester logTester = new LogTester();
@@ -79,8 +80,8 @@ public class MigrationEsClientImplTest {
     underTest.addMappingToExistingIndex("as", "s", "new_field", "keyword", mappingOptions);
 
     assertThat(loadExistingIndices()).toIterable().contains("as");
-    ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetadata>> mappings = mappings();
-    MappingMetadata mapping = mappings.get("as").get("s");
+    Map<String, MappingMetadata> mappings = mappings();
+    MappingMetadata mapping = mappings.get("as");
     assertThat(countMappingFields(mapping)).isOne();
     assertThat(field(mapping, "new_field")).isNotNull();
 
@@ -99,10 +100,10 @@ public class MigrationEsClientImplTest {
   }
 
   private Iterator<String> loadExistingIndices() {
-    return es.client().getMapping(new GetMappingsRequest()).mappings().keysIt();
+    return es.client().getMapping(new GetMappingsRequest()).mappings().keySet().iterator();
   }
 
-  private ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetadata>> mappings() {
+  private Map<String, MappingMetadata> mappings() {
     return es.client().getMapping(new GetMappingsRequest()).mappings();
   }
 
index dc23867022a11af9aed3da461376e7796be728e5..c006a2f7291df23a0bac0d78be421ce447b523cf 100644 (file)
@@ -26,13 +26,13 @@ import java.util.Set;
 import java.util.stream.Collectors;
 import org.apache.commons.lang.StringUtils;
 import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
-import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
 import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest;
 import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest;
 import org.elasticsearch.action.support.master.AcknowledgedResponse;
 import org.elasticsearch.client.indices.CreateIndexRequest;
 import org.elasticsearch.client.indices.CreateIndexResponse;
 import org.elasticsearch.client.indices.GetIndexRequest;
+import org.elasticsearch.client.indices.PutMappingRequest;
 import org.elasticsearch.cluster.health.ClusterHealthStatus;
 import org.elasticsearch.common.settings.Settings;
 import org.sonar.api.Startable;
@@ -153,14 +153,12 @@ public class IndexCreator implements Startable {
     }
     client.waitForStatus(ClusterHealthStatus.YELLOW);
 
-    // create types
-    LOGGER.info("Create type {}", builtIndex.getMainType().format());
+    LOGGER.info("Create mapping {}", builtIndex.getMainType().getIndex().getName());
     AcknowledgedResponse mappingResponse = client.putMapping(new PutMappingRequest(builtIndex.getMainType().getIndex().getName())
-      .type(builtIndex.getMainType().getType())
       .source(builtIndex.getAttributes()));
 
     if (!mappingResponse.isAcknowledged()) {
-      throw new IllegalStateException("Failed to create type " + builtIndex.getMainType().getType());
+      throw new IllegalStateException("Failed to create mapping " + builtIndex.getMainType().getIndex().getName());
     }
     client.waitForStatus(ClusterHealthStatus.YELLOW);
   }
index acc06c89066cbfde1d7028d05c8ac8c218728bfc..56f309a48d0848d4dd49903c2550ce0281f5399d 100644 (file)
@@ -76,7 +76,6 @@ import org.sonar.core.util.stream.MoreCollectors;
 import org.sonar.server.es.BaseDoc;
 import org.sonar.server.es.EsClient;
 import org.sonar.server.es.EsUtils;
-import org.sonar.server.es.IndexType;
 import org.sonar.server.es.SearchOptions;
 import org.sonar.server.es.Sorting;
 import org.sonar.server.es.searchrequest.RequestFiltersComputer;
@@ -637,11 +636,9 @@ public class IssueIndex {
 
     BoolQueryBuilder viewsFilter = boolQuery();
     for (String viewUuid : viewUuids) {
-      IndexType.IndexMainType mainType = TYPE_VIEW;
       viewsFilter.should(QueryBuilders.termsLookupQuery(FIELD_ISSUE_BRANCH_UUID,
         new TermsLookup(
-          mainType.getIndex().getName(),
-          mainType.getType(),
+          TYPE_VIEW.getIndex().getName(),
           viewUuid,
           ViewIndexDefinition.FIELD_PROJECTS)));
     }
@@ -1319,11 +1316,9 @@ public class IssueIndex {
   private static SearchSourceBuilder prepareNonClosedVulnerabilitiesAndHotspotSearch(String projectUuid, boolean isViewOrApp) {
     BoolQueryBuilder componentFilter = boolQuery();
     if (isViewOrApp) {
-      IndexType.IndexMainType mainType = TYPE_VIEW;
       componentFilter.filter(QueryBuilders.termsLookupQuery(FIELD_ISSUE_BRANCH_UUID,
         new TermsLookup(
-          mainType.getIndex().getName(),
-          mainType.getType(),
+          TYPE_VIEW.getIndex().getName(),
           projectUuid,
           ViewIndexDefinition.FIELD_PROJECTS)));
     } else {
index 51653b0d04759a409b565cc93f0a269c6c6ebcc2..253d55f62b5cad8c50edb57be4b391e6846741fa 100644 (file)
  */
 package org.sonar.server.es;
 
-import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Sets;
 import java.util.Map;
 import java.util.function.Consumer;
 import javax.annotation.CheckForNull;
-import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest;
 import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest;
 import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest;
 import org.elasticsearch.action.get.GetRequest;
 import org.elasticsearch.action.index.IndexRequest;
 import org.elasticsearch.action.support.WriteRequest;
+import org.elasticsearch.client.indices.GetMappingsRequest;
 import org.elasticsearch.cluster.metadata.MappingMetadata;
-import org.elasticsearch.common.collect.ImmutableOpenMap;
 import org.elasticsearch.common.settings.Settings;
 import org.junit.Rule;
 import org.junit.Test;
@@ -64,11 +62,11 @@ public class IndexCreatorTest {
   @Rule
   public EsTester es = EsTester.createCustom();
 
-  private MetadataIndexDefinition metadataIndexDefinition = new MetadataIndexDefinition(new MapSettings().asConfig());
-  private MetadataIndex metadataIndex = new MetadataIndexImpl(es.client());
-  private TestEsDbCompatibility esDbCompatibility = new TestEsDbCompatibility();
-  private MapSettings settings = new MapSettings();
-  private MigrationEsClient migrationEsClient = mock(MigrationEsClient.class);
+  private final MetadataIndexDefinition metadataIndexDefinition = new MetadataIndexDefinition(new MapSettings().asConfig());
+  private final MetadataIndex metadataIndex = new MetadataIndexImpl(es.client());
+  private final TestEsDbCompatibility esDbCompatibility = new TestEsDbCompatibility();
+  private final MapSettings settings = new MapSettings();
+  private final MigrationEsClient migrationEsClient = mock(MigrationEsClient.class);
 
   @Test
   public void create_index() {
@@ -98,20 +96,20 @@ public class IndexCreatorTest {
 
     IndexMainType fakeIndexType = main(Index.simple("fakes"), "fake");
     String id = "1";
-    es.client().index(new IndexRequest(fakeIndexType.getIndex().getName(), fakeIndexType.getType()).id(id).source(new FakeDoc().getFields())
+    es.client().index(new IndexRequest(fakeIndexType.getIndex().getName()).id(id).source(new FakeDoc().getFields())
       .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE));
-    assertThat(es.client().get(new GetRequest(fakeIndexType.getIndex().getName(), fakeIndexType.getType(), id)).isExists()).isTrue();
+    assertThat(es.client().get(new GetRequest(fakeIndexType.getIndex().getName()).id(id)).isExists()).isTrue();
 
     // v2
     run(new FakeIndexDefinitionV2());
 
-    ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetadata>> mappings = mappings();
-    MappingMetadata mapping = mappings.get("fakes").get("fake");
+    Map<String, MappingMetadata> mappings = mappings();
+    MappingMetadata mapping = mappings.get("fakes");
     assertThat(countMappingFields(mapping)).isEqualTo(3);
     assertThat(field(mapping, "updatedAt")).containsEntry("type", "date");
     assertThat(field(mapping, "newField")).containsEntry("type", "integer");
 
-    assertThat(es.client().get(new GetRequest(fakeIndexType.getIndex().getName(), fakeIndexType.getType(), id)).isExists()).isFalse();
+    assertThat(es.client().get(new GetRequest(fakeIndexType.getIndex().getName()).id(id)).isExists()).isFalse();
   }
 
   @Test
@@ -122,7 +120,8 @@ public class IndexCreatorTest {
     run(new FakeIndexDefinition());
 
     // v2
-    assertThatThrownBy(() -> run(new FakeIndexDefinitionV2()))
+    FakeIndexDefinitionV2 definitionV2 = new FakeIndexDefinitionV2();
+    assertThatThrownBy(() -> run(definitionV2))
       .isInstanceOf(IllegalStateException.class)
       .hasMessageContaining("Blue/green deployment is not supported. Elasticsearch index [fakes] changed and needs to be dropped.");
   }
@@ -174,8 +173,8 @@ public class IndexCreatorTest {
     assertThat(logTester.logs(LoggerLevel.INFO))
       .doesNotContain(LOG_DB_VENDOR_CHANGED)
       .doesNotContain(LOG_DB_SCHEMA_CHANGED)
-      .contains("Create type fakes/fake")
-      .contains("Create type metadatas/metadata");
+      .contains("Create mapping fakes")
+      .contains("Create mapping metadatas");
   }
 
   @Test
@@ -227,8 +226,8 @@ public class IndexCreatorTest {
     run(new FakeIndexDefinition());
     assertThat(logTester.logs(LoggerLevel.INFO))
       .doesNotContain(expectedLog)
-      .contains("Create type fakes/fake")
-      .contains("Create type metadatas/metadata");
+      .contains("Create mapping fakes")
+      .contains("Create mapping metadatas");
     putFakeDocument();
     assertThat(es.countDocuments(FakeIndexDefinition.INDEX_TYPE)).isOne();
 
@@ -238,14 +237,14 @@ public class IndexCreatorTest {
 
     assertThat(logTester.logs(LoggerLevel.INFO))
       .contains(expectedLog)
-      .contains("Create type fakes/fake")
+      .contains("Create mapping fakes")
       // keep existing metadata
-      .doesNotContain("Create type metadatas/metadata");
+      .doesNotContain("Create mapping metadatas");
     // index has been dropped and re-created
     assertThat(es.countDocuments(FakeIndexDefinition.INDEX_TYPE)).isZero();
   }
 
-  private ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetadata>> mappings() {
+  private Map<String, MappingMetadata> mappings() {
     return es.client().getMapping(new GetMappingsRequest()).mappings();
   }
 
@@ -269,13 +268,12 @@ public class IndexCreatorTest {
   }
 
   private void putFakeDocument() {
-    es.putDocuments(FakeIndexDefinition.INDEX_TYPE, ImmutableMap.of("key", "foo"));
+    es.putDocuments(FakeIndexDefinition.INDEX_TYPE, Map.of("key", "foo"));
   }
 
   private void verifyFakeIndexV1() {
-    ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetadata>> mappings = mappings();
-    MappingMetadata mapping = mappings.get("fakes").get("fake");
-    assertThat(mapping.type()).isEqualTo("fake");
+    Map<String, MappingMetadata> mappings = mappings();
+    MappingMetadata mapping = mappings.get("fakes");
     assertThat(mapping.getSourceAsMap()).isNotEmpty();
     assertThat(countMappingFields(mapping)).isEqualTo(2);
     assertThat(field(mapping, "updatedAt")).containsEntry("type", "date");
index 89f2dd8874ab09e86b88446d493a7299e253a373..d41f8f26dc6db7281d8bd304b5d92e6aa3e80609 100644 (file)
@@ -28,7 +28,6 @@ import org.sonar.core.util.stream.MoreCollectors;
 import org.sonar.server.es.EsClient;
 
 import static org.sonar.server.permission.index.FooIndexDefinition.DESCRIPTOR;
-import static org.sonar.server.permission.index.FooIndexDefinition.TYPE_AUTHORIZATION;
 
 public class FooIndex {
 
@@ -41,7 +40,7 @@ public class FooIndex {
   }
 
   public boolean hasAccessToProject(String projectUuid) {
-    SearchHits hits = esClient.search(EsClient.prepareSearch(DESCRIPTOR.getName(), TYPE_AUTHORIZATION.getType())
+    SearchHits hits = esClient.search(EsClient.prepareSearch(DESCRIPTOR.getName())
       .source(new SearchSourceBuilder().query(QueryBuilders.boolQuery()
         .must(QueryBuilders.termQuery(FooIndexDefinition.FIELD_PROJECT_UUID, projectUuid))
         .filter(authorizationTypeSupport.createQueryFilter()))))