J.J
J.J

Reputation: 51

Joining two feature collections by ID in Earth Engine Javascript API

I simply want to join the two collections in the way, that the joined feature collection has all properties of the primary and secondary feature collections.

// Create the primary collection.
var primaryFeatures = ee.FeatureCollection([
  ee.Feature(null, {foo: 0, ID: 'a'}),
  ee.Feature(null, {foo: 1, ID: 'b'}),
  ee.Feature(null, {foo: 1, ID: 'c'}),
  ee.Feature(null, {foo: 2, ID: 'd'}),
]);

// Create the secondary collection.
var secondaryFeatures = ee.FeatureCollection([
  ee.Feature(null, {bar: 1, ID: 'a'}),
  ee.Feature(null, {bar: 1, ID: 'b'}),
  ee.Feature(null, {bar: 2, ID: 'c'}),
  ee.Feature(null, {bar: 3, ID: 'd'}),
]);

// Use an equals filter to specify how the collections match.
var toyFilter = ee.Filter.equals({
  leftField: 'ID',
  rightField: 'ID'
});

// Define the join.
var innerJoin = ee.Join.simple()

// Apply the join.
var toyJoin = innerJoin.apply(primaryFeatures, secondaryFeatures,  toyFilter);


// Print the result.
print('Inner join toy example:', toyJoin);

The final toyJoin feature collection should have 5 Feature with the 3 properties ID, foo and bar. Thank you very much!

Upvotes: 1

Views: 3947

Answers (1)

Nicholas Clinton
Nicholas Clinton

Reputation: 893

I don't expect 5 features in the output because you only have four unique IDs and a 1:1 relationship between the IDs in your input collections. Regardless, to get an inner join, use ee.Join.inner(). To merge the results, map over the inner join:

// Create the primary collection.
var primaryFeatures = ee.FeatureCollection([
  ee.Feature(null, {foo: 0, ID: 'a'}),
  ee.Feature(null, {foo: 1, ID: 'b'}),
  ee.Feature(null, {foo: 1, ID: 'c'}),
  ee.Feature(null, {foo: 2, ID: 'd'}),
]);

// Create the secondary collection.
var secondaryFeatures = ee.FeatureCollection([
  ee.Feature(null, {bar: 1, ID: 'a'}),
  ee.Feature(null, {bar: 1, ID: 'b'}),
  ee.Feature(null, {bar: 2, ID: 'c'}),
  ee.Feature(null, {bar: 3, ID: 'd'}),
]);

// Use an equals filter to specify how the collections match.
var toyFilter = ee.Filter.equals({
  leftField: 'ID',
  rightField: 'ID'
});

// Define the join.
var innerJoin = ee.Join.inner();

// Apply the join.
var toyJoin = innerJoin.apply(primaryFeatures, secondaryFeatures,  toyFilter);

// Print the result.
print('Inner join toy example:', toyJoin);

print(toyJoin.map(function(pair) {
  var f1 = ee.Feature(pair.get('primary'));
  var f2 = ee.Feature(pair.get('secondary'));
  return f1.set(f2.toDictionary());
}));

Upvotes: 4

Related Questions