2015-12-22 50 views
1

我想在網站中實現谷歌分析庫,以使我自己的查詢和獲得某種數據來管理它們之後。製作自己的查詢谷歌分析(JAVA)

我跟着這個例子,一切正常。但是,我只能編寫示例查詢(上週的訪問者)。我已經閱讀了許多有關這方面的信息和文檔,而且我仍然遇到同樣的問題。

我確定必須有一種方法來實現這一點,但實際上我無法編寫任何代碼來進行自己的查詢。

的代碼是(我使用maven):

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; 
import com.google.api.client.http.HttpTransport; 
import com.google.api.client.json.JsonFactory; 
import com.google.api.client.json.gson.GsonFactory; 

import com.google.api.services.analytics.Analytics; 
import com.google.api.services.analytics.AnalyticsScopes; 
import com.google.api.services.analytics.model.Accounts; 
import com.google.api.services.analytics.model.GaData; 
import com.google.api.services.analytics.model.Profiles; 
import com.google.api.services.analytics.model.Webproperties; 

import java.io.File; 
import java.io.IOException; 

/** 
* A simple example of how to access the Google Analytics API using a service 
* account. 
*/ 
public class test { 

    private static final String APPLICATION_NAME = "example"; 
    private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); 
    private static final String KEY_FILE_LOCATION = //route to p.12 file; 
    private static final String SERVICE_ACCOUNT_EMAIL = //mail example; 


    public static void main(String[] args) { 
     try { 

      Analytics analytics = initializeAnalytics(); 

      String profile = getFirstProfileId(analytics); 
      System.out.println("First Profile Id: " + profile); 
      printResults(getResults(analytics, profile)); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    private static Analytics initializeAnalytics() throws Exception { 
     // Initializes an authorized analytics service object. 

     // Construct a GoogleCredential object with the service account email 
     // and p12 file downloaded from the developer console. 
     HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); 
     GoogleCredential credential = new GoogleCredential.Builder() 
       .setTransport(httpTransport) 
       .setJsonFactory(JSON_FACTORY) 
       .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) 
       .setServiceAccountPrivateKeyFromP12File(new File(KEY_FILE_LOCATION)) 
       .setServiceAccountScopes(AnalyticsScopes.all()) 
       .build(); 

     // Construct the Analytics service object. 
     return new Analytics.Builder(httpTransport, JSON_FACTORY, credential) 
       .setApplicationName(APPLICATION_NAME).build(); 
    } 

    private static String getFirstProfileId(Analytics analytics) throws IOException { 
     // Get the first view (profile) ID for the authorized user. 
     String profileId = null; 

     // Query for the list of all accounts associated with the service account. 
     Accounts accounts = analytics.management().accounts().list().execute(); 

     if (accounts.getItems().isEmpty()) { 
      System.err.println("No accounts found"); 
     } else { 
      String firstAccountId = accounts.getItems().get(0).getId(); 

      // Query for the list of properties associated with the first account. 
      Webproperties properties = analytics.management().webproperties() 
        .list(firstAccountId).execute(); 

      if (properties.getItems().isEmpty()) { 
       System.err.println("No Webproperties found"); 
      } else { 
       String firstWebpropertyId = properties.getItems().get(0).getId(); 

       // Query for the list views (profiles) associated with the property. 
       Profiles profiles = analytics.management().profiles() 
         .list(firstAccountId, firstWebpropertyId).execute(); 

       if (profiles.getItems().isEmpty()) { 
        System.err.println("No views (profiles) found"); 
       } else { 
        // Return the first (view) profile associated with the property. 
        profileId = profiles.getItems().get(0).getId(); 
       } 
      } 
     } 
     return profileId; 
    } 

    private static GaData getResults(Analytics analytics, String profileId) throws IOException { 
     // Query the Core Reporting API for the number of sessions 
     // in the past seven days. 
     return analytics.data().ga() 
       .get("ga:" + profileId, "7daysAgo", "today", "ga:sessions") 
       .execute(); 
    } 

    private static void printResults(GaData results) { 
     // Parse the response from the Core Reporting API for 
     // the profile name and number of sessions. 
     if (results != null && !results.getRows().isEmpty()) { 
      System.out.println("View (Profile) Name: " 
        + results.getProfileInfo().getProfileName()); 
      System.out.println("Total Sessions: " + results.getRows().get(0).get(0)); 
     } else { 
      System.out.println("No results found"); 
     } 
    } 

} 

需要注意的是,使查詢的代碼是:

private static GaData getResults(Analytics analytics, String profileId) throws IOException { 
    // Query the Core Reporting API for the number of sessions 
    // in the past seven days. 
    return analytics.data().ga() 
      .get("ga:" + profileId, "7daysAgo", "today", "ga:sessions") 
      .execute(); 
} 

的問題是:我怎麼設置我的查詢的尺寸使用這個代碼?

此查詢的工作(無尺寸):

private static GaData getMobileTraffic(Analytics analytics, String profileId) throws IOException { 
     return analytics.data().ga() 
       .get("ga:" + profileId, "30daysAgo", "today", "ga:sessions, ga:pageviews, ga:sessionDuration") 
       .execute(); 
    } 

這一個不(大小)工作:

private static GaData getMobileTraffic(Analytics analytics, String profileId) throws IOException { 
     return analytics.data().ga() 
       .get("ga:" + profileId, "30daysAgo", "today", "ga:sessions, ga:pageviews, ga:sessionDuration",**"ga:userType"**) 
       .execute(); 
    } 

我希望得到任何幫助。非常感謝!

+1

第二個代碼示例不執行查詢,它返回ID爲第一數據視圖在您的憑證授權的第一個帳戶中。實際查詢位於getResults方法中,具體爲analytics.data()。ga()。get(「ga:」+ profileId,「7daysAgo」,「today」,「ga :會話「)執行(); (從視圖標識數據返回,從7天前直到今天,會話數量爲度量標準)。這是你需要改變的路線。 –

+0

你是對的@EikePierstorff。我編輯了我的答案。不幸的是,問題仍然存在 –

+0

文檔中有一個完整的示例,這沒有幫助(https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide)?維度和指標參考顯示您可以查詢哪些值(https://developers.google.com/analytics/devguides/reporting/core/dimsmets)。度量(數字)作爲get方法中的第四個參數添加到查詢中(在您的示例中爲ga:sessions,多個度量使用逗號分隔列表),並且可以將setDimensions方法鏈接到分類數據(即。 setDimensions(「ga:source,ga:keyword」)。 –

回答

0

好吧,似乎我終於解決了我的問題。我回答自己是爲了幫助有類似問題的人,並希望他們也能爲他們工作。

答案很簡單,關於Google Analytics的文檔有點令人困惑,但如果有人想要添加維度,則只需在以下鏈接中添加代碼(或編輯Google Analytics中的示例查詢):

https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide

剛剛添加該代碼只是下面的查詢示例(如果你想添加的尺寸):

setDimensions("ga:userType") 

所以,最終的代碼將是:

private static GaData getMobileTraffic(Analytics analytics, String profileId) throws IOException { 
     return analytics.data().ga() 
       .get("ga:" + profileId, "30daysAgo", "today", "ga:sessions, ga:pageviews, ga:sessionDuration").setDimensions("ga:userType") 
       .execute(); 
    } 

注意的是,在主代碼,您需要添加打印功能,就像這樣:

public static void main(String[] args) { 
    try { 
     Analytics analytics = initializeAnalytics(); 
     printMobileTraffic(getMobileTraffic(analytics, profile)); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
}